我的模型很简单,一个客户可以有很多电话号码:
我在实体框架中代表了这一点
生成的客户端类如下.
public partial class Client { public Client() { this.PhoneNumbers = new HashSet<PhoneNumber>(); } public int Id { get; set; } public string Name { get; set; } public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; } }
现在我需要为“创建客户端”创建一个视图页面.此页面还应有空间输入PhoneNumbers(例如:默认情况下应该有两个文本框来输入电话号码)
<fieldset> <legend>Client</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <p> <input type="submit" value="Create" /> </p> </fieldset>
作为上面的“创建视图”,我们可以轻松地为“model.Name”提供空间,因为它是一个简单的属性.但是我怎么能做类似的电话号码收集.. ??
我知道我们可以通过丑陋的javascript代码实现这一点,但我想知道最简单易用的方法,我们可以使用ASP.NET MVC ……?
解决方法
你必须做一些事情:
public class Clientviewmodel { public int Id {get;set;} public string Name {get;set;} public PhoneNumber PhoneNumber1 {get;set;} public PhoneNumber PhoneNumber2 {get;set;} }
更改Create以返回Clientviewmodel
[HttpGet] public ActionResult Create() { return View(new Clientviewmodel()); }
映射HttpPost以使用Clientviewmodel并将值映射到它:
[HttpPost] public ActionResult Create(Clientviewmodel clientviewmodel) { var client = new Client(); client.Name = clientviewmodel.Name; client.PhoneNumbers.Add(clientviewmodel.PhoneNumber1); client.PhoneNumbers.Add(clientviewmodel.PhoneNumber2); db.Clients.Add(client); db.SaveChanges(); return RedirectToAction("Index","Client"); }
然后,最后,修改您的视图:
<fieldset> <legend>Client</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.PhoneNumber1.Number) </div> <div class="editor-field"> @Html.EditorFor(model => model.PhoneNumber1.Number) @Html.ValidationMessageFor(model => model.PhoneNumber1.Number) </div> <div class="editor-label"> @Html.LabelFor(model => model.PhoneNumber2.Number) </div> <div class="editor-field"> @Html.EditorFor(model => model.PhoneNumber2.Number) @Html.ValidationMessageFor(model => model.PhoneNumber2.Number) </div> <p> <input type="submit" value="Create" /> </p> </fieldset>