如何创建/使用的一种形式和模型粘合剂从View =&GT通过收藏;调节器 [英] How do I create/use a form and model-binder to pass collections from View => Controller
问题描述
我有一个MVC 4剃刀查看我通过视图模型与用户的集合
和实体的集合
。
I have an MVC 4 Razor view that I passed a view model with a collection of User
and a collection of Entities
.
有关这个问题的目的,让我们说我想要一个新的用户
添加到每个实体
。所以,我有,你输入用户名,然后该用户名和实体被发送到一个控制器方法的文本域 ADDUSER(用户用户的IEnumerable<实体>经济需求测试)
这种方法可以替代地 ADDUSER(长用户ID,IEnumerable的< TPkey>键)
。 ADDUSER
得到用户
和实体
和需要照顾添加用户
到每个实体
取值
For the purposes of this question, let's say I'm trying to add a new User
to each of the Entities
. So I have a text form field where you enter a username and then the that username and the entities is sent to a controller method AddUser(User user, IEnumerable<Entity> ents)
this method could alternatively be AddUser(long UserId, IEnumerable<TPkey> keys)
. AddUser
gets the User
and Entity
s and takes care of adding the User
to each of the Entity
s
所以,我应该如何去传递的的IEnumerable&LT; TPkey&GT;
到控制器的方法
So, how should I go about passing the the IEnumerable<TPkey>
to the controller method?
这是也有些由该控制器需要处理不同类型的主键的事实复杂化了。
This is also somewhat complicated by the fact that the the controller needs to handle different types of primary keys.
现在我这样做:
@using (Html.BeginForm("AddUser", ViewContext.RouteData.Values["Controller"].ToString()))
{
<label for="user"> Username (or Email) to grant access:</label>
<input type="text" name="user" />
<input type="submit" value="Grant Access" />
foreach (var item in Model.Entities)
{
<input type="hidden" name="keys" value="@item.PKey" />
}
}
这是否有意义?我想preFER使用过的钥匙控制器的更强类型的方法是,因为现在我在做钥匙串的一些粗略的分析,我会preFER要能森过强/通用类型的对象。
Does that make sense? I would prefer to be using a more strongly typed method of passing the keys to the controller, because right now I'm having to do some sketchy parsing of the string of keys, and I would prefer to be able to sen over a strongly/generic typed object.
推荐答案
要列出是另一个类的对象集合的模型属性,试试这个:
To list a model property that is a collection of objects of another class, try this:
Class Person {
public int id {get; set;}
public string name {get; set;}
public List<Car> Cars {get; set;}
}
Class Car {
public int id {get; set; }
public string name {get; set;}
}
在视图中,必须列出从person对象车上对象与属性名和索引中指定的输入
in view, you must list the car objects from person object as inputs named with the property name and a index
@using (Html.BeginForm("AddUser", ViewContext.RouteData.Values["Controller"].ToString()))
{
<label for="name"> </label>
<input type="text" name="name" />
int counter = 0;
foreach (var item in Model.Entities)
{
<input type="hidden" name="Cars[@counter.ToString()].id" value="@item.PKey" />
<input type="hidden" name="Cars[@counter.ToString()].name" value="@item.name" />
counter++;
}
<input type="submit" value="Grant Access" />
}
使用这个工具,你的模型从形式
Using this, your model automatically populate the property Cars with the inputs sent from the form
这篇关于如何创建/使用的一种形式和模型粘合剂从View =&GT通过收藏;调节器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!