MVC复杂类型的模型绑定
Posted 分而治之
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC复杂类型的模型绑定相关的知识,希望对你有一定的参考价值。
1,复杂类型
//模型范例 public class Contact { public string Name { get; set; } public string PhoneNo { get; set; } public string EmailAddress { get; set; } public Address Address { get; set; } } public class Address { public string Province { get; set; } public string City { get; set; } public string District { get; set; } public string Street { get; set; } }
//请求表单范例 <input id="Name" name="Name" type="text" ... /> <input id="PhoneNo" name="PhoneNo" type="text" ... /> <input id="EmailAddress" name="EmailAddress" type="text" ... /> <input id="Address_Province" name="Address.Province" type="text" ... /> <input id="Address_City" name="Address.City" type="text" ... /> <input id="Address_District" name="Address.District" type="text" ... /> <input id="Address_Street" name="Address.Street" type="text"... />
public ActionResult Action(Contact foo, Contact bar){}
2,基于名称的数组绑定(名称必须相同)
//数据源范例 <input name="Foo" type="text" value="123"/> <input name="Foo" type="text" value="456" /> <input name="Foo" type="text" value="789" />
Public ActionResult ActionMethod(string[] foo){}
3,基于索引的绑定(索引必须从0开始,且连续,不连续会导致后面的绑定失败)
//请求表单范例 <input name="[0].Name" type="text" value="" .../> <input name="[1].Name" type="text" value="" .../>
public ActionResult Index(string[] array){}
4,集合(除数组和字典之外的所有实现IEnumerable<T>接口的类型)
//请求表单范例 <input name="[0].Name" type="text" value="" .../> <input name="[0].PhoneNo" type="text" value="" .../> <input name="[0].EmailAddress" type="text" value="" .../> <input name="[1].Name" type="text" value="" .../> <input name="[1].PhoneNo" type="text" value="" .../> <input name="[1].EmailAddress" type="text" value="" .../>
//范例 public ActionResult Action(IEnumerable<Contact> contacts){
foreach (Contact contact in contacts){}
}
5,字典(实现了接口IDictionary<TKey,TValue>的类型)
//请求表单范例 <input name="[0].Key" type="text" value="Foo" .../> <input name="[0].Value.Name" type="text" value="" .../> <input name="[0].Value.PhoneNo" type="text" value="139" .../> <input name="[0].Value.EmailAddress" type="text" value="[email protected]" .../> <input name="[0].Name" type="text" value="Bar" .../> <input name="[1].Value.Name" type="text" value="Bar" .../> <input name="[1].Value.PhoneNo" type="text" value="138" .../> <input name="[1].Value.EmailAddress" type="text" value="[email protected]" .../>
public ActionResult Action(IDictionary<string, Contact> contacts) { foreach (string key in contacts.Keys) { Response.Write(key + "<br/>"); Contact contact = contacts[key]; Response.Write(string.Format(" {0}: {1}<br/>","Name", contact.Name)); Response.Write(string.Format(" {0}: {1}<br/>","PhoneNo", contact.PhoneNo)); Response.Write(string.Format(" {0}: {1}<br/><br/>", "EmailAddress", contact.EmailAddress)); } }
以上是关于MVC复杂类型的模型绑定的主要内容,如果未能解决你的问题,请参考以下文章