2014-12-28 46 views
0

不知道哪個部分是錯誤的。我已成功顯示視圖內的複選框列表,但是當它回發給控制器時,CheckBoxViewModel模型返回null。 ASP.NET MVC查看模型null當傳回複選框到控制器

public class CheckBoxViewModel { 
    public List<CheckBoxList> CheckBoxLists {get; set;} 
} 

public class CheckBoxList{ 
    public int CheckBoxId {get; set;} 
    public string CheckBoxDescription { get; set;} 
    public bool CheckBoxState {get; set;} 
} 

@model CheckBoxViewModel 

foreach(var item in Model.CheckBoxLists) { 
    @Html.CheckBoxFor(model => model.CheckBoxState, new { id = @model.CheckBoxId }): 
    @Html.DisplayFor(model => model.CheckBoxDescription); 
} 


[HttpPost] 
public ActionResult EditCheckBox(int userId, CheckBoxViewModel model) { 
} 
+0

你的'form'看起來像什麼? – beautifulcoder

回答

2

這裏有雲的完整解決方案 -

我用了你同樣的ViewModels -

public ActionResult AddQuestion() 
{ 
    CheckBoxViewModel m = new CheckBoxViewModel(); 
    m.CheckBoxLists = new List<CheckBoxList>(); 
    m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi1", CheckBoxId = 1, CheckBoxState = true}); 
    m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi2", CheckBoxId = 2, CheckBoxState = true }); 
    m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi3", CheckBoxId = 3, CheckBoxState = true }); 
    return View(m); 
} 
-

public class CheckBoxViewModel 
{ 
    public List<CheckBoxList> CheckBoxLists { get; set; } 
} 

public class CheckBoxList 
{ 
    public int CheckBoxId { get; set; } 
    public string CheckBoxDescription { get; set; } 
    public bool CheckBoxState { get; set; } 
} 

然後我就GET行動與一些樣本數據來創建

相應的GET查看 -

@model WebApplication1.Controllers.CheckBoxViewModel 

@{ 
    ViewBag.Title = "AddQuestion"; 
} 

<h2>AddQuestion</h2> 

@using (Html.BeginForm("EditCheckBox", "Home")) 
{ 
    for (int i = 0; i < Model.CheckBoxLists.Count; i++) 
    { 
     @Html.CheckBox(
      String.Format("CheckBoxLists[{0}].CheckBoxState", i.ToString()), 
      Model.CheckBoxLists[i].CheckBoxState, 
      new { id = Model.CheckBoxLists[i].CheckBoxId }) 
     @Html.Label(Model.CheckBoxLists[i].CheckBoxDescription) 

     @Html.Hidden(String.Format("CheckBoxLists[{0}].CheckBoxDescription", i.ToString()), Model.CheckBoxLists[i].CheckBoxDescription) 
     @Html.Hidden(String.Format("CheckBoxLists[{0}].CheckBoxId", i.ToString()), Model.CheckBoxLists[i].CheckBoxId) 
    } 

    <input type="submit" value="Click" /> 
} 

然後最後POST行動 -

[HttpPost] 
public ActionResult EditCheckBox(int? userId, CheckBoxViewModel model) 
{ 
    return null; 
} 

這裏是頁面的外觀 -

enter image description here

當我運行的代碼,然後點擊按鈕,我得到的模型如下圖所示 -

enter image description here

相關問題