【问题标题】:ASP.NET MVC 5 Html.CheckboxFor only return default value on postASP.NET MVC 5 Html.CheckboxFor 仅在发布时返回默认值
【发布时间】:2016-03-08 05:32:28
【问题描述】:

我已阅读教程并为该页面准备了一个复选框列表。提交表单时,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);
}

【问题讨论】:

  • 您似乎向我们展示了错误的模型视图中的模型是SelectStudentViewModel,但您显示的唯一模型是SelectStudentModel

标签: asp.net-mvc checkboxlist


【解决方案1】:

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

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

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

【讨论】:

  • 就是这样。从来不知道这会导致问题。
  • 你这里也有很多不好的做法。也许您只显示了视图的一部分,但视图中的模型只需要为List&lt;SelectStudentModel&gt;(您不需要另一个类来包装它)。并且视图模型不应包含作为数据模型的对象或集合(您应该使用的是仅包含视图中需要的那些属性的视图模型)。并且视图模型不应该从数据模型中调用方法。您使您的应用无法进行单元测试(如果您确实需要如图所示的视图模型,则从控制器填充集合)
  • 刚开始使用 ASP.NET MVC。发现pattern生成了很多类:P
  • 每个视图都应该有一个对应的视图模型,一旦你开始认真地用MVC开发你就会发现。从长远来看,它将为您节省大量时间。另见What is ViewModel in MVC?
  • 您能推荐一些资源,我可以在其中找到漂亮而优雅的 ASP.NET MVC 教程吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2016-07-17
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2013-01-31
相关资源
最近更新 更多