![](/img/trans.png)
[英]Model binding with nested child models and PartialViews in ASP.NET MVC
[英]Binding Model of PartialViews on a POST
我有一個復雜的模型類,如:
public class Client
{
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string AddressLine { get; set; }
}
我的視圖由幾個 Partial 組成,我將模型的一部分傳遞給它們並設置一些用於編輯的字段:
在 Index.cshtml 中
@using (Html.BeginForm("Index"))
{
@Html.DisplayNameFor(modelItem => model.Name)
@Html.DisplayFor(modelItem => model.Name)
<div id="divAddress">
@Html.Action("_Address", model.Address)
</div>
<div>RESULT MESSAGE GOES HERE!</div>
<input type="submit" value="Submit" />
}
在_Address.cshtml
@Html.DisplayNameFor(modelItem => model.AdressLine)
@Html.EditorFor(modelItem => model.AdressLine)
在代碼隱藏中,我的 Actions 包含兩個簡單的 ActionResults 方法:
[HttpGet]
public ActionResult Index()
{
Client = new Client();
Client.Name = "António Fonseca"
return View(model);
}
[HttpPost]
public ActionResult Index(Client model)
{
return View(model);
}
public ActionResult _Address(Address model)
{
return View(model);
}
當我提交表單,我需要調用的充分WebService的Client
結構,並顯示它的結果消息。 發生的情況是,當點擊Index(model) -> model.Address
為空。 它只有在遇到_Address(model)
方法時才會被綁定。
有沒有辦法使用 PartialViews在主 Action 中綁定完整的類結構?
將_Address.cshtml
的模型更改為與主視圖中的模型相同並使用@Html.Action("_Address", model)
以便正確命名表單控件 - 即name="Address.AdressLine"
(它的當前只是name="AdressLine"
但您的模型不包含名為AdressLine
的屬性)。
@model Client
@Html.DisplayNameFor(m => m.Address.AdressLine)
@Html.EditorFor( m=> m.Address.AdressLine)
但是,使用@Html.Action()
不是正確的方法。 您應該使用EditorTemplate
。 將_Address.cshtml
重命名為Address.cshtml
(以匹配您的類名)並將其放置在/Views/Shared/EditorTemplates
文件夾中,然后在視圖中使用
@Html.EditorFor(m => m.Address)
這將正確命名您的表單控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.