【问题标题】:Custom Model Binder not updating自定义模型绑定器未更新
【发布时间】:2014-01-17 15:35:06
【问题描述】:

我一直在处理一个 MVC 项目,该项目有一个复杂的模型,其中包含多个嵌套类,一个类中嵌套了另一个类。我可以让所有其他复杂类型正确更新,但最后一个永远不会正确更新。我确保注册了它的自定义模型绑定器,它会被执行并返回一个对象,并为其属性分配适当的值,但原始模型永远不会更新。

我已经剪掉了所有有效的东西,只留下我的结构:

public class Case
{
    public Case()
    {
        PersonOfConcern = new Person();
    }

    public Person PersonOfConcern { get; set; }
}

[ModelBinder(typeof(PersonModelBinder))]
public class Person
{
    public Person()
    {
        NameOfPerson = new ProperName();
    }

    public ProperName NameOfPerson { get; set; }
}

[TypeConverter(typeof(ProperNameConverter))]
public class ProperName : IComparable, IEquatable<string>
{
    public ProperName()
        : this(string.Empty)
    { }

    public ProperName(string fullName)
    {
        /* snip */
    }

    public string FullName { get; set; }
}

模型绑定器

public class PersonModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(Person))
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            string prefix = bindingContext.ModelName + ".";

            if (request.Form.AllKeys.Contains(prefix + "NameOfPerson"))
            {
                return new Person()
                {
                    NameOfPerson = new ProperName(request.Form.Get(prefix + "NameOfPerson"))
                };
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

控制器

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    if (CurrentUser.HasAccess)
    {
        Case item = _caseData.Get(id);

        if (TryUpdateModel(item, "Case", new string[] { /* other properties removed */ }, new string[] { "PersonOfConcern" })
            && TryUpdateModel(item.PersonOfConcern, "Case.PersonOfConcern"))
        {
            // ... Save here.
        }
    }
}

我已经束手无策了。 PersonModelBinder 被执行并返回正确的值集,但模型永远不会更新。我在这里错过了什么?

【问题讨论】:

  • 您找到解决方案了吗?我现在也遇到了同样的问题。
  • 嗯,是的……但我通过改变方法解决了这个问题。我改为使用基本的 ViewModel。现在,我在我的模型类中嵌套类,但我只是在我的 ViewModel 类中使用 .NET 原语,并且在我的 HttpPost 操作中,我将 ViewModel 数据映射到模型。如果您想了解更多详细信息,我可以将其与其他一些信息一起发布作为答案。
  • 太好了,我最终也找到了类似的解决方法。非常感谢您花时间回复。

标签: c# asp.net-mvc asp.net-mvc-4 model-binding custom-model-binder


【解决方案1】:

我认为你应该在 Application_Start 的全局 asax 中添加它

 ModelBinders.Binders.Add(typeof(PersonModelBinder ), new PersonModelBinder ());

【讨论】:

  • 谢谢,但我试过了。如果我没有添加活页夹,我的自定义模型活页夹根本不会被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多