对象中对象的 MVC 绑定列表
MVC Binding List of Objects in Object
我正在尝试动态构建一个需要在提交表单时绑定到 ViewModel 的 table。
第一项是提交表单的操作。然后是父 ViewModel,然后是子 ViewModel。下面是两个文本字段,代表我需要绑定的数据。
当我提交表单时,页面中的所有其他字段都绑定到它们各自的 属性 但 ProgramViewModels 的复杂对象不是。
我错过了什么?
public ActionResult Add(AddEntityViewModel viewModel){
Code that does something
}
public class AddEntityViewModel
{
public IList<int> Counties { get; set; }
public IList<ProgramViewModel> Programs { get; set; }
public IList<int> Regions { get; set; }
public string EntityName { get; set; }
public bool IsValid()
{
if (string.IsNullOrEmpty(EntityName))
return false;
if (Counties == null || Counties.Count == 0)
return false;
if (Programs == null || Programs.Count == 0)
return false;
if (Regions == null || Regions.Count == 0)
return false;
return true;
}
}
public class ProgramViewModel
{
public int Id;
public string SystemId;
}
<input type="hidden" id="Programs[0]__Id" name="Programs[0].Id" data-programid="3" value="3">
<input type="text" id="Programs[0]__SystemId" name="Programs[0].SystemId" style="width:100%" maxlength="50">
更新:
在 adiga 的回答后将字段更改为属性。但这也没有解决问题。
public class ProgramViewModel
{
public int Id { get; set; }
public string SystemId { get; set; }
}
如果您有一个对象列表,您应该执行一个 foreach 指令来获取所有对象:
<% foreach(var x in values) { %>
<div>hello <%= x.name %></div>
<% } %>
您的 ProgramViewModel
包含字段。将它们更改为属性。
public class ProgramViewModel
{
public int Id { get; set; }
public string SystemId { get; set; }
}
DefaultModelBinder
使用反射并仅绑定属性而不绑定字段。
我正在尝试动态构建一个需要在提交表单时绑定到 ViewModel 的 table。
第一项是提交表单的操作。然后是父 ViewModel,然后是子 ViewModel。下面是两个文本字段,代表我需要绑定的数据。
当我提交表单时,页面中的所有其他字段都绑定到它们各自的 属性 但 ProgramViewModels 的复杂对象不是。
我错过了什么?
public ActionResult Add(AddEntityViewModel viewModel){
Code that does something
}
public class AddEntityViewModel
{
public IList<int> Counties { get; set; }
public IList<ProgramViewModel> Programs { get; set; }
public IList<int> Regions { get; set; }
public string EntityName { get; set; }
public bool IsValid()
{
if (string.IsNullOrEmpty(EntityName))
return false;
if (Counties == null || Counties.Count == 0)
return false;
if (Programs == null || Programs.Count == 0)
return false;
if (Regions == null || Regions.Count == 0)
return false;
return true;
}
}
public class ProgramViewModel
{
public int Id;
public string SystemId;
}
<input type="hidden" id="Programs[0]__Id" name="Programs[0].Id" data-programid="3" value="3">
<input type="text" id="Programs[0]__SystemId" name="Programs[0].SystemId" style="width:100%" maxlength="50">
更新:
在 adiga 的回答后将字段更改为属性。但这也没有解决问题。
public class ProgramViewModel
{
public int Id { get; set; }
public string SystemId { get; set; }
}
如果您有一个对象列表,您应该执行一个 foreach 指令来获取所有对象:
<% foreach(var x in values) { %>
<div>hello <%= x.name %></div>
<% } %>
您的 ProgramViewModel
包含字段。将它们更改为属性。
public class ProgramViewModel
{
public int Id { get; set; }
public string SystemId { get; set; }
}
DefaultModelBinder
使用反射并仅绑定属性而不绑定字段。