您使用 EditorTemplates 的方法是正确的,但请记住,您需要填充CityDropDown
。因此,视图应该像这样传递:
Person model = new Person()
{
Address = new Address
{
CityDropDown = new SelectListItem[]{
new SelectListItem { Selected = true, Text = "Select one..." },
new SelectListItem { Text = "Anywhere", Value = "Anywhere" },
new SelectListItem { Text = "Somewhere", Value = "Somewhere" },
new SelectListItem { Text = "Nowhere", Value = "Nowhere" }
}
}
};
这将使该视图仅包含:
@Html.EditorForModel()
然后你的EditorTemplates
会从那里接:
〜/Views/shared/EditorTemplates/Address.cshtml(注:这是基于type不是属性名称)
@model MvcApplication.Models.Address
@Html.DropDownListFor(x => x.City, Model.CityDropDown)
@Html.EditorFor(x => x.Zip)
〜/Views/Shared/EditorTemplates/Person.cshtml
@model MvcApplication.Models.Person
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Name)
@Html.EditorFor(x => x.Address)
<input type="submit" value="Save" />
}
三个视图然后呈现如下内容:
<form action="/" method="post">
<input class="text-box single-line" id="Name" name="Name" type="text" value="" />
<select id="Address_City" name="Address.City">
<option selected="selected">Select one...</option>
<option value="Anywhere">Anywhere</option>
<option value="Somewhere">Somewhere</option>
<option value="Nowhere">Nowhere</option>
</select>
<input class="text-box single-line" id="Address_Zip" name="Address.Zip" type="text" value="" />
<input type="submit" value="Save" />
示例项目可以在这里找到:https://github.com/bchristie/StackOverflow-Examples/tree/master/questions-19247958 https://github.com/bchristie/StackOverflow-Examples/tree/master/questions-19247958