ASP.NET MVC 5 Html.CheckboxFor 仅 return 默认值 post

ASP.NET MVC 5 Html.CheckboxFor only return default value on post

我已阅读教程并准备了页面的复选框列表。提交表单时,Selected 属性 只得到值 false。 我错过了什么吗? 模特

public class SelectStudentModel
{           
    public int StudentID { get; set; }    
    public string CardID { get; set; }    
    public string Name { get; set; }    
    public bool Selected { get; set;}
}

视图模型

public class SelectStudentViewModel
{
    public List<SelectStudentModel> VMList;
    public SelectStudentViewModel()
    {
        VMList = SelectStudentModel.GETStudent();
    }
}

景色

@using Student.Models
@model SelectStudentViewModel
@using (Html.BeginForm("AddStudent", "SectionStudent", FormMethod.Post, new { @role = "form" }))
{
    @{ for (int i = 0; i < Model.VMList.Count(); i++)
    {
        <tr>
            <td>@Html.CheckBoxFor(m => m.VMList[i].Selected)</td>
            <td>@Html.DisplayFor(model => model.VMList[i].Name)</td>
        </tr>
    }
}
 <input type="submit" value="submit" />
}@* end form *@

发布数据的控制器

[HttpPost]
public ActionResult AddStudent(SelectStudentViewModel model)
{
    foreach (SelectStudentModel m in model.VMList)
    {
        Console.Write(m.Selected.ToString());
    }
    return PartialView("StudentSelectForm", model);
}

VMList 是您的 SelectStudentViewModel 模型中的一个字段。您需要将其更改为 属性(带有 getter/setter),以便 DefaultModelBinder 可以 设置

public class SelectStudentViewModel
{
    public List<SelectStudentModel> VMList { get; set; } // change
    public SelectStudentViewModel()
    {
        VMList = SelectStudentModel.GETStudent();
    }
}

旁注:建议您将 @Html.DisplayFor(model => model.VMList[i].Name) 更改为 @Html.LabelFor(m => m.VMList[i].Selected, Model.MList[i].Name) 以便获得与复选框关联的标签