Csharp/C#教程:MVC表单模型为复杂对象集合返回null分享


MVC表单模型为复杂对象集合返回null

我有一个包含4行的表格(移动,工作,单元格,电子邮件)和5列以上。 当我发布POST时,我没有收到任何数据。 我可以重构代码以使其工作吗?

型号

public class ContactInfoViewModel { public string HomePhone { get; set; } public ICollection HomePhoneChecks { get; set; } public string MobilePhone { get; set; } public ICollection MobilePhoneChecks { get; set; } public string WorkPhone { get; set; } public ICollection WorkPhoneChecks { get; set; } public string Email { get; set; } public ICollection EmailChecks { get; set; } public string Email2 { get; set; } public IEnumerable Rows { get; set; } public IEnumerable GetAllRows() { return new List { new RowData { Name = "HomePhone", Label = "Home Phone", Heading = HomePhone, Columns = HomePhoneChecks}, new RowData { Name = "MobilePhone", Label = "Mobile Phone", Heading = MobilePhone, Columns = MobilePhoneChecks}, new RowData { Name = "WorkPhone", Label = "Work Phone", Heading = WorkPhone, Columns = WorkPhoneChecks}, new RowData { Name = "Email", Label = "Email", Heading = Email, Columns = EmailChecks}, }; } public class RowData { public string Name { get; set; } public string Label { get; set; } public string Heading { get; set; } public ICollection Columns { get; set; } } 

查看

 @foreach (var row in Model.ContactInfo.GetAllRows()) {   
@row.Label
@Html.TextBoxFor(m => row.Heading)
@foreach (var item in row.Columns) { @Html.CheckBoxFor(m => item) }

}

我会更改您的模型集合以使用能够进行模型绑定的List属性。

举个例子:

  public List AllRows { get; set; } 

然后将循环更改为此模型绑定器将拾取的循环。

  @for (int i = 0; i < Model.AllRows.Count; i++) { ..... @Html.EditorFor(model => Model.AllRows[i].Heading) ..... } 

然后将它们发回服务器。

有关它的更多信息,请参见此处:

https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

上述就是C#学习教程:MVC表单模型为复杂对象集合返回null分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/961602.html

(0)
上一篇 2021年11月26日
下一篇 2021年11月26日

精彩推荐