2010-07-08 100 views
1

我的問題是,當我提交表單並返回類型QuestionViewModel的viewModel - 類型爲null。ASP.net,MVC 2 - 發佈視圖模型

查看下面的代碼。

我的控制器:

public ActionResult Create() 
    { 
     var viewModel = new QuestionViewModel { 
      Question = question, 
      Type = questionType, 
      Types = surveyDB.QuestionTypes.ToList() 
     }; 
     return View(viewModel); 
    } 

在我看來:
`

<h2>Skapa en fråga</h2> 
<% Html.EnableClientValidation(); %> 

<% using (Html.BeginForm()) {%> 
    <%: Html.ValidationSummary(true) %> 

     <%:Html.EditorFor(model => model.Question, new { Types = Model.Types }) %> 

     <% switch (Model.Question.Type) { 
       case 1: 
        Response.Write(Html.EditorFor(model => model.Type)); 
        break; 

       default: 

        break; 
      } 
      %> 

     <p> 
      <input type="submit" value="Skapa" /> 
     </p> 

<% } %> 

`

凡編輯器model.Question是

<%: Html.LabelFor(model => model.Type) %> 
<%:Html.DropDownList("Type", new SelectList(ViewData["Types"] as IEnumerable,"Id","Type", Model.Type), "Välj en frågetyp")%> 
<% if((int)ViewData["type"] > 0) { %> 
<div class="editor-label"> 
    <%: Html.LabelFor(model => model.Text) %> 
</div> 
<div class="editor-field"> 
    <%: Html.TextBoxFor(model => model.Text) %> 
    <%: Html.ValidationMessageFor(model => model.Text) %> 
</div> 

而對於model.Type

<%: Html.LabelFor(model => model.Alternative) %> 
<%: Html.TextAreaFor(model => model.Alternative, new { @Class="alternatives" })%> 
<%: Html.ValidationMessageFor(model => model.Alternative)%> 

編輯我現在提交我會在這裏結束:

[HttpPost] 
    public ActionResult Create(QuestionViewModel viewModel) 
    { 
     **// This becomes null** 
     string alternatives = viewModel.Type.Alternatives; 
    } 

我的視圖模型看起來像這樣

namespace ASurvey.ViewModels { 
    public class QuestionViewModel { 
     public Question Question { get; set; } 
     public List<QuestionType> Types { get; set; } 
     public MultipleChoice Type { get; set; } 
    } 
} 
+1

MultipleChoice是否有默認的構造函數,以便MVC可以創建它?你沒有發佈代碼。 – queen3 2010-07-08 14:28:18

回答

1

在你的問題編輯器中你的代碼是Html.DropDownList("Type" ...。看起來它覆蓋了你的QuestionViewModel.Type編輯器。

嘗試在問題編輯器中使用Html.DropDownListFor(x => x.Type ...。它會將名稱歸爲「Question.Type」,但不僅僅是「Type」。