重命名 HTML 名称属性以将数据导入模型
Rename HTML name attribute to get data into model
我在使用 post 将数据从表单传递到我的模型时遇到问题。
我有以下代码:
public ActionResult Edit(int? id)
{
...
return this.View("Edit", Tuple.Create(staff, team);
}
如您所见,我正在向视图返回一个元组,因为我需要有多个模型。我想我通常会创建一个 ViewModel,但在这种情况下,我认为这就够了。
将元组、列表甚至字典返回到视图通常有什么问题吗?我应该始终创建 ViewModel 吗?
这是视图:
@model Tuple<Staff, List<Team>>
@{
var staff = Model.Item1;
var teams = Model.Item2;
}
@using(Html.BeginForm())
{
...
@Html.LabelFor(model => staff.Foo)
@Html.EditorFor(model => staff.Bar)
}
@using(Html.BeginForm())
{
...
@Html.LabelFor(model => team.Foo)
@Html.EditorFor(model => team.Bar)
}
无论如何,这段代码呈现如下:
<input type="text" ... name="staff.Foo" ... />
和
<input type="text" ... name="team.Foo" ... />
这是我的目标控制器(当我提交表单时"staff"):
[HttpPost]
public ActionResult Edit([Bind(Include = "foo,bar")] Staff staff)
{
...
this.DbContext.SaveChanges();
...
}
问题是,数据将通过 post 发送,但我的模型一直为空。我想这是因为我将我的模型作为元组传递给了视图。
即使我改变
@Html.EditorFor(model => model.Item1.Foo)
将会
<input type="text" ... name="Item1.Foo" ... />
我该如何解决这个问题。我找不到将名称属性重命名为 "Foo" 而不是 "staff.Foo" 的解决方案。我想这会解决问题。我真的必须创建一个 ViewModel 吗?
此致
如果你只是发一个复杂的属性的model/tuple,你可以使用Bind.Prefix
属性
[HttpPost]
public ActionResult Edit([Bind(Prefix="staff")] Staff model)
这有效地从属性中删除了 staff.
前缀,因此 staff.Foo
变为 Foo
并将绑定到 class Staff
,但是我强烈建议使用视图模型而不是 Tuple
(而且它实际上代码更少)。
我在使用 post 将数据从表单传递到我的模型时遇到问题。
我有以下代码:
public ActionResult Edit(int? id)
{
...
return this.View("Edit", Tuple.Create(staff, team);
}
如您所见,我正在向视图返回一个元组,因为我需要有多个模型。我想我通常会创建一个 ViewModel,但在这种情况下,我认为这就够了。 将元组、列表甚至字典返回到视图通常有什么问题吗?我应该始终创建 ViewModel 吗?
这是视图:
@model Tuple<Staff, List<Team>>
@{
var staff = Model.Item1;
var teams = Model.Item2;
}
@using(Html.BeginForm())
{
...
@Html.LabelFor(model => staff.Foo)
@Html.EditorFor(model => staff.Bar)
}
@using(Html.BeginForm())
{
...
@Html.LabelFor(model => team.Foo)
@Html.EditorFor(model => team.Bar)
}
无论如何,这段代码呈现如下:
<input type="text" ... name="staff.Foo" ... />
和
<input type="text" ... name="team.Foo" ... />
这是我的目标控制器(当我提交表单时"staff"):
[HttpPost]
public ActionResult Edit([Bind(Include = "foo,bar")] Staff staff)
{
...
this.DbContext.SaveChanges();
...
}
问题是,数据将通过 post 发送,但我的模型一直为空。我想这是因为我将我的模型作为元组传递给了视图。 即使我改变
@Html.EditorFor(model => model.Item1.Foo)
将会
<input type="text" ... name="Item1.Foo" ... />
我该如何解决这个问题。我找不到将名称属性重命名为 "Foo" 而不是 "staff.Foo" 的解决方案。我想这会解决问题。我真的必须创建一个 ViewModel 吗?
此致
如果你只是发一个复杂的属性的model/tuple,你可以使用Bind.Prefix
属性
[HttpPost]
public ActionResult Edit([Bind(Prefix="staff")] Staff model)
这有效地从属性中删除了 staff.
前缀,因此 staff.Foo
变为 Foo
并将绑定到 class Staff
,但是我强烈建议使用视图模型而不是 Tuple
(而且它实际上代码更少)。