【问题标题】:Remove prefix from posted data in asp.net mvc从 asp.net mvc 中的发布数据中删除前缀
【发布时间】:2015-04-22 18:34:02
【问题描述】:

我的视图如下所示。每个字段都在 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();
        }

【问题讨论】:

  • 我已经看过了。这是自定义模型绑定器的示例。我的要求与此类似,但不完全相同。我的表单数据具有前缀值,我想在模型绑定发生之前去除该前缀值,以便它可以绑定到我的模型

标签: asp.net-mvc asp.net-mvc-4 model-view-controller modelbinder


【解决方案1】:

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

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

    ...
}

【讨论】:

  • 下面的代码不起作用,Name 属性的值现在只是前缀:public ActionResult Save([Bind(Prefix = "prefix")]string Name) { throw new NotImplementedException(); }
【解决方案2】:

您可以为他使用BindAttribute

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

}

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

【讨论】:

    【解决方案3】:

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

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

    感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2015-11-15
      • 1970-01-01
      相关资源
      最近更新 更多