繁体   English   中英

重命名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();
   ...
}

问题是,数据将通过邮寄发送,但我的模型始终保持空白。 我猜这是由于我将模型作为元组传递给视图的缘故。 即使我改变

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

将会

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

我怎样才能解决这个问题。 我找不到找到将name属性重命名为“ Foo”而不是“ staff.Foo”的解决方案。 我想这会解决问题。 我真的必须创建一个ViewModel吗?

最好的祝福

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

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

这有效地剥夺了staff. 从属性中staff.Foo前缀,以便staff.Foo变为Foo并将绑定到class Staff ,但是我强烈建议使用视图模型而不是Tuple (无论如何实际上它的代码更少)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM