这是使用EditorTemplate
. 我对您的模型类进行了细微更改(这可行;但是,请注意,这只是为了让您理解这个概念。您可以对此进行扩展)
楷模
public class SomeExampleModel
{
public int Id { get; set; }
public string Name { get; set;}
public string Street { get; set; }
public IList<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public int SomeExampleModelId { get; set; }
public ContactType Type { get; set; }
public string ContactText { get { return Type.ToString(); } }
public string ContactValue { get; set; }
}
public enum ContactType
{
email,
Phone,
mobile,
fax
}
记下我创建了一个ContactText
返回枚举文本的属性(用于显示目的)
为联系人创建一个编辑器模板(命名为Contact.cshtml
;模板名称必须与类名匹配)。在屏幕截图下方找到放置编辑器模板的位置。
这是代码Contact.cshtml
@model Test1.Models.Contact
<table>
@Html.HiddenFor(a=>a.Type)
<tr>
<td>@Html.Label(Model.ContactText)</td>
<td>@Html.TextBoxFor(a => a.ContactValue)</td>
</tr>
</table>
这是“创建”视图的代码(ExampleCreateView.cshtml
在我的例子中)
@model Test1.Models.SomeExampleModel
@{
ViewBag.Title = "ExampleCreateView";
}
<h2>ExampleCreateView</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>SomeExampleModel</legend>
@Html.HiddenFor(model=>model.Id)
<table>
<tr>
<td>@Html.LabelFor(model=>model.Name)</td>
<td>@Html.EditorFor(model=>model.Name)</td>
</tr>
<tr>
<td>@Html.LabelFor(model=>model.Street)</td>
<td>@Html.EditorFor(model=>model.Street)</td>
</tr>
<tr>
<td>@Html.LabelFor(model=>model.Contacts)</td>
<td>@Html.EditorFor(model=>model.Contacts)</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
记下我是如何使用@Html.EditorFor
该Contacts
物业的。
下面是 Get、Post 操作的样子
public ActionResult ExampleCreateView()
{
SomeExampleModel model = new SomeExampleModel();
Contact contactEmail = new Contact();
contactEmail.Type = ContactType.email;
Contact contactFax = new Contact();
contactFax.Type = ContactType.fax;
Contact contactPhone = new Contact();
contactPhone.Type = ContactType.Phone;
Contact contactMobile = new Contact();
contactMobile.Type = ContactType.mobile;
List<Contact> contacts = new List<Contact>();
contacts.Add(contactEmail);
contacts.Add(contactFax);
contacts.Add(contactPhone);
contacts.Add(contactMobile);
model.Contacts = contacts;
return View(model);
}
[HttpPost]
public ActionResult ExampleCreateView(SomeExampleModel model)
{
//Your operations
return View(model);
}
运行应用程序。这就是视图的样子
您将在 POST 操作中获得的内容的屏幕截图