简体   繁体   English

自定义模型活页夹未更新

[英]Custom Model Binder not updating

I've been working on an MVC project that has a complex model with several nested classes, and one class has another class nested in it. 我一直在从事一个MVC项目,该项目具有一个带有几个嵌套类的复杂模型,而一个类又嵌套了另一个类。 I can get all of the other complex types to update correctly, but this last one never updates correctly. 我可以使所有其他复杂类型正确更新,但是最后一个永远不会正确更新。 I've made sure to register its custom model binder, which gets executed and returns an object with the proper values assigned to its properties, but the original model never gets updated. 我已经确定要注册其自定义模型联编程序,该联编程序将被执行并返回一个为其属性分配了适当值的对象,但是原始模型永远不会更新。

I've snipped out everything that works, leaving my structure only below: 我已经摘录了所有有效的内容,仅将我的结构留在下面:

Classes 班级

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; }
}

Model Binder 模型活页夹

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);
    }
}

Controller 控制者

[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.
        }
    }
}

I'm at my wits' end. 我尽力了。 The PersonModelBinder gets executed and returns the correct set of values, but the model never gets updated. PersonModelBinder被执行并返回正确的值集,但模型从未更新。 What am I missing here? 我在这里想念什么?

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

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

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

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