重命名HTML名称属性以将数据导入模型

时间:2015-01-09 10:24:22

标签: c# asp.net-mvc

我在使用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" ... />

这是我的目标控制器(当我提交表格“工作人员”时):

[HttpPost]
public ActionResult Edit([Bind(Include = "foo,bar")] Staff staff)
{
   ...
   this.DbContext.SaveChanges();
   ...
}

问题是,数据将通过邮件发送,但我的模型一直空着。我想这是因为我将我的模型作为元组传递给了视图。 即使我改变了

@Html.EditorFor(model => model.Item1.Foo)

将是

<input type="text" ... name="Item1.Foo" ... />

我该如何解决这个问题。我找不到将name属性重命名为“Foo”而不是“staff.Foo”的解决方案。我想这可以解决问题。我真的需要创建一个ViewModel吗?

祝你好运

1 个答案:

答案 0 :(得分:0)

如果您只发布模型/元组的一个复杂属性,则可以使用Bind.Prefix属性

[HttpPost]
public ActionResult Edit([Bind(Prefix="staff")] Staff model)

这有效地剥离了属性中的staff.前缀,因此staff.Foo变为Foo并且将绑定到类Staff,但我强烈建议使用视图模型而不是Tuple(实际上它的代码实际上更少)。