Asp.net mvc ASP.NET MVC 5 Html.CheckboxFor仅在post时返回默认值

Asp.net mvc ASP.NET MVC 5 Html.CheckboxFor仅在post时返回默认值,asp.net-mvc,checkboxlist,Asp.net Mvc,Checkboxlist,我已经阅读了教程并为页面准备了一个复选框列表。提交表单时,所选属性仅获取值false。 我错过了什么吗? 模型 public class SelectStudentModel { public int StudentID { get; set; } public string CardID { get; set; } public string Name { get; set; } public bool Select

我已经阅读了教程并为页面准备了一个复选框列表。提交表单时,所选属性仅获取值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();
    }
}

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

public class SelectStudentViewModel
{
    public List<SelectStudentModel> VMList { get; set; } // change
    public SelectStudentViewModel()
    {
        VMList = SelectStudentModel.GETStudent();
    }
}
公共类SelectStudentViewModel
{
公共列表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)
这样您就可以得到一个与复选框关联的标签

您似乎向我们显示了错误的模型视图中的模型是
SelectStudentViewModel
,但您显示的唯一模型是
SelectStudentModel
。不知道这会导致问题。你在这里也有很多不好的做法。也许您只显示了视图的一部分,但是视图中的模型只需要是
列表
(您不需要另一个类来包装它)。视图模型不应包含作为数据模型的对象或集合(您应该使用的是仅包含需要在视图中显示的属性的视图模型)。视图模型不应该从数据模型调用方法。刚刚开始使用ASP.NET MVC时,您已经使应用程序无法进行单元测试(如果您确实需要如图所示的视图模型,则从控制器填充集合)。发现该模式生成了很多类:每个视图都应该有一个相应的视图模型,一旦你开始认真地在MVC中开发,你就会发现这一点。从长远来看,这将为你节省大量时间。另请参阅您是否推荐一些源代码,在这些源代码中我可以找到ASP.NET MVC的精美教程?
[HttpPost]
public ActionResult AddStudent(SelectStudentViewModel model)
{
    foreach (SelectStudentModel m in model.VMList)
    {
        Console.Write(m.Selected.ToString());
    }
    return PartialView("StudentSelectForm", model);
}
public class SelectStudentViewModel
{
    public List<SelectStudentModel> VMList { get; set; } // change
    public SelectStudentViewModel()
    {
        VMList = SelectStudentModel.GETStudent();
    }
}