2016-02-18 74 views
-1

無論我在我的post方法中做了什麼,該模型的答案爲null。查看模型沒有得到回報後

index.cshtml

@using WebPortal.Classes 
@using WebPortal.Models 
@model WebPortal.Models.QuestionsAnswersViewModel 

@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Index</h2> 
@using (Html.BeginForm("index", "QuestionFormResponses", FormMethod.Post)) 
{ 
    @Html.AntiForgeryToken() 

if (Model != null) 
{ 
    string category = ""; 
    string column = ""; 

    foreach (Answer answer in Model.Answers) 
    { 
     if (answer.Question.QuestionCategory.Category != category) 
     { 
      category = answer.Question.QuestionCategory.Category; 
      <h1>@category</h1> 
     } 

     if (answer.QuestionCategoryColumn.ColumnName != column) 
     { 
      column = answer.QuestionCategoryColumn.ColumnName; 
      <h4>@column</h4> 
     } 

     Html.HiddenFor(x => x.Answers); 

     <p>@answer.Question.QuestionText: </p> 
     <input type="text" name="@answer.Id" value="@answer.QuestionAnswer"/> 

    } 
      <input type="submit" value="Submit" class="btn btn-default"/> 
} 

視圖模型

namespace WebPortal.Models 
    { 
     public class QuestionsAnswersViewModel 
     { 
      public List<Answer> Answers { get; set; } 
     } 
    } 

POST方法

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Index(QuestionsAnswersViewModel m) 
    { 

應答模型

namespace WebPortal.Models 
{ 
public class Answer 
{ 
    public int Id { get; set; } 
    public int QuestionId { get; set; } 
    public virtual Question Question { get; set; } 
    public int QuestionFormResponseId { get; set; } 
    public virtual QuestionFormResponse QuestionFormResponse { get; set; } 
    public int QuestionCategoryColumnId { get; set; } 
    public virtual QuestionCategoryColumn QuestionCategoryColumn { get; set; } 
    public object QuestionAnswer { get; set; } 

} 
} 

我在帖子的第一行放置了一箇中斷點,然後看看m中的內容。 m總是有答案被設置爲null。即使視圖模型在過去到前端時已滿,並且前端可以顯示其中的內容。

Headers for the post

Params for the post

+0

首先,您的輸入元素缺少'name'和'value'屬性的引號。另外,請包括您的答案模型代碼。 – timothyclifford

+0

@timothyclifford添加了答案模型。我會看看引號。自從我使用變量以來,我不認爲我需要它們,但我也可以考慮這一點。 – user3113278

+0

你的整個行動方法在哪裏? –

回答

0

編輯:

改變了我的前端代碼如下。前端看起來很糟糕,但現在回帖

@using (Html.BeginForm("index", "QuestionFormResponses", FormMethod.Post)) 
{ 
    @Html.AntiForgeryToken() 

if (Model != null) 
{ 

    for (int i = 0; i < Model.Answers.Count; i++) 
    { 

     <table> 
      <tr><th> 
       @Html.DisplayFor(a => a.Answers[i].QuestionCategoryColumn.QuestionCategory.Category) 
      </th></tr> 
      <tr> 
       <td>@Html.DisplayFor(a => a.Answers[i].QuestionCategoryColumn.ColumnName)</td> 
       <td>@Html.DisplayFor(a => a.Answers[i].Question.QuestionText)</td> 
       <td>@Html.TextBoxFor(a => a.Answers[i].QuestionAnswer)</td> 
      </tr> 
     </table> 
    } 

      <input type="submit" value="Submit" class="btn btn-default"/> 
} 

}