Question

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. 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. What am I missing here?

No correct solution

OTHER TIPS

i think you should add it in global asax on Application_Start

 ModelBinders.Binders.Add(typeof(PersonModelBinder ), new PersonModelBinder ());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top