我有一个班级“客户”和“地址”。每个客户可以拥有多个地址,即邮政和住宅。
我创建了它们的ModelView以用于剃刀中的数据输入: 模型视图:
Public class Client
{
public int ClientID { get; set; }
public string ClientName {get;set;}
}
Public class Addresses
{
public int ClientID { get; set; }
public int AddressType {get;set;}
public string Addr {get;set;}
}
Public class ClientsInfoModelView
{
public Client clnt{get;set;}
public List<Addresses> addr {get;set;}
}
Controller(ClientsController):
Public ActionResult Index()
{
ClientsInfoModelView _MV = new ClientsInfoModelView();
_MV.clnt = Context.Client.FirstOrDefault(w=> w.ClientID=1);
_MV.Addr = Context.Addresses.FirstOrDefault(w=> w.ClientID=1);
return View("index",_MV);
}
Public ActionResult SAVE(ClientsInfoModelView data)
{
// here data.addr is null, where as clnt has data as per filled in the form
}
Razor
@model ModelViews. ClientsInfoModelView
@using (Html.beginform(“SAVE”,”Clients”,FormMethod.post))
{
@html.TextBoxFor(m=> m. ClientID);
@html.TextBoxFor(m=> m. ClientName);
Address:
Postal: @html.TextBoxFor(m=> m. addr(w=> w. AddressType==1). Addr)
Residential: @html.TextBoxFor(m=> m. addr(w=> w. AddressType==2). Addr)
<button type=”submit”> Save </button>
}
显示效果很好。我可以看到为客户端填充的数据以及地址,但是在单击“保存”按钮的地方出现问题。控制器为Addr属性接收null,该属性引用List。
答案 0 :(得分:0)
好吧,我不认为您可以使用以下语法将文本框绑定到模型
@html.TextBoxFor(m=> m. addr(w=> w. AddressType==1). Addr)
这是因为addr的类型不是方法。很明显,接下来要想的是用where子句编写相同的语法,例如..
@Html.TextBoxFor(m => m.addr.Where(o=>o.AddressType == 1).Select(p=>p.Addr).FirstOrDefault());
但是这也会抛出运行时异常,因为where子句可能会返回0到n个元素,并且compilar无法理解要绑定哪个元素。
<强>解决方案:强>
首先从列表中获取住宅和邮政地址块的索引,并直接使用该索引来解析 addr 列表。
@{int postalAddressIndex = @Model.addr.FindIndex(o => o.AddressType == 1);
int residentialAddressIndex = @Model.addr.FindIndex(o => o.AddressType == 2);}
@using (Html.BeginForm("SAVE","Client",FormMethod.Post))
{
@Html.TextBoxFor(m=> m. clnt.ClientID)
@Html.TextBoxFor(m => m.clnt.ClientName)
<br/>
@Html.Label("Address:")
<br/>
@Html.LabelFor(m=> m.addr[postalAddressIndex].AddressType,"Postal:")
@Html.TextBoxFor(m=> m.addr[postalAddressIndex].Addr);
@Html.HiddenFor(m => m.addr[postalAddressIndex].AddressType);
@Html.HiddenFor(m => m.addr[postalAddressIndex].ClientID);
<br/>
@Html.LabelFor(m => m.addr[residentialAddressIndex].AddressType, "Residential:")
@Html.TextBoxFor(m => m.addr[residentialAddressIndex].Addr);
@Html.HiddenFor(m => m.addr[residentialAddressIndex].AddressType);
@Html.HiddenFor(m => m.addr[residentialAddressIndex].ClientID);
<button type="submit"> Save </button>