如何在模型中将行添加到集合列表? [英] How can I add rows to a collection list in my Model?
问题描述
为简单起见,假设我有一个User
模型,其中List<Email>
作为其属性之一.
For the sake of simplicity, let's say I have a User
model that has a List<Email>
as one of its properties.
public class UserModel
{
public string UserName { get; set; }
public List<Email> Emails = new List<Email>();
}
public class Email
{
public string Address { get; set; }
}
在我看来,我有一封电子邮件列表:
In my view, I have a list of the emails:
<table>
@foreach(Email email in Model.Emails)
{
<tr>
<td>@Html.EditorFor(modelItem => email.Address)</td>
</tr>
}
</table>
现在让我们说我希望用户能够单击向表添加新行的按钮,以便用户可以向绑定到其用户的列表中添加新的电子邮件.我该怎么做呢?我是否需要以某种方式通过javascript添加新行,以便在发布页面时将其绑定到模型?我不知道该如何解决这个问题,因为我是WebForms的MVC相对较新的人.
Now let's say I want the user to be able to click a button that adds a new row to the table so that the user can add a new Email to the List that is bound to their User. How do I do this? Do I need to add the new row via javascript in a certain way so that it gets bound to the model when the page is posted? I have no idea how to approach this as I'm relatively new to MVC coming from WebForms.
推荐答案
After some researching, I found this blog post by Steven Anderson http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
它似乎完全可以满足我的要求(除了它是用MVC2编写的).
It appears to be doing exactly what I want (except it is written in MVC2).
这篇关于如何在模型中将行添加到集合列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!