1

我有一个如下所示的视图。每个字段都在 name 属性中附加了一个前缀,但我后端中的模型具有没有前缀的属性。

@using (Html.BeginForm("Save", "Home", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <input type="hidden" name="prefix" value="prefix"/>
        <input type="text" id="prefix.Name" name="prefix.Name"/>
        <input type="submit" value="submit" />
    </fieldset>
}

我的操作方法如下所示:

public ActionResult Save([ModelBinder(typeof(CustomModelBinder))]Employee employee)
        {
            throw new NotImplementedException();
        }

我的模型看起来像:

public class Employee
    {
        public string Name { get; set; }
    }

有人可以帮助我如何通过自定义模型绑定器来实现这一点,我想从每个发布的表单项名称中去除前缀​​。

发布的表格数据:

prefix:prefix
prefix.Name:Hello World!!

我也尝试了下面的代码,但它不起作用。有人可以解释这里出了什么问题。

public ActionResult Save([Bind(Prefix = "prefix")]Employee employee)
        {
            throw new NotImplementedException();
        }
4

3 回答 3

2

尝试添加绑定前缀值,如下所示:

public ActionResult SetPassword([Bind(Prefix = "Form")] UserSetPasswordForm form)
{
    if (!ModelState.IsValid)
    {
        ....
    }

    ...
}
于 2015-04-22T18:57:18.537 回答
0

你可以用BindAttribute他的

public ActionResult Submit([Bind(Prefix = "L")] string[] longPropertyName) {

}

这里有一个与您类似的问题: Asp.Net MVC 2 - Bind a model's property to a different named value

于 2015-04-22T18:56:54.450 回答
0

有一些奇怪的行为,当我改变我的前缀值时它开始工作。

public ActionResult Save([Bind(Prefix = "**someothervalue**")]Employee employee)
        {
            throw new NotImplementedException();
        }

感谢大家的帮助。

于 2015-04-22T20:01:52.443 回答