4

我的模型很简单,一个客户可以有多个电话号码:

我已经在实体框架中表示了这一点

生成的客户端类如下。

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; }
}

现在我需要为“创建客户端”创建一个视图页面。此页面也应该有空间输入电话号码(例如:默认情况下应该有两个文本框来输入电话号码)

<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 ...?

4

2 回答 2

6

你必须做几件事:

首先创建一个ViewModel具有您需要的属性:

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>
于 2013-07-12T12:27:55.560 回答
2

对于集合,您可以使用以下内容:

@for(int i = 0; i < Model.PhoneNumbers.Count; i++)
{
   <div class="editor-field">
        @Html.EditorFor(model => model.PhoneNumbers[i])
        @Html.ValidationMessageFor(model => model.PhoneNumbers[i])
    </div>
}
于 2013-07-13T14:50:38.110 回答