Search code examples
asp.net-mvc-3custom-model-binder

MVC 3 Custom Model Binding To Flat Form Variable Structure


I'm having difficulty getting a Custom Model Binder working when the request contains a flat collection of form variables.

I've got a ViewModel class that contains a nested ViewModel, e.g.

public class ViewModel1
{
    public long Id { get; set; }
    public ViewModel2 NestedType { get; set; }
}

public class ViewModel2
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

My problem is, if I use Fiddler to submit a request with a form variable of NestedType.Name, then my custom model binder executes fine, however, the request I'm having to deal with is out of my control, in this case, it's posted via an ajax request from a JQGrid instance and is 'flat' i.e.

Id=5
Name=firstname
Surname=surname

not

Id=5
NestedType.Name=firstname
NestedType.Surname=surname

Is there any way I can get this to work?

Thanks in advance.

EDIT:

To clarify a bit, my controller action looks like this:

public ActionResult GridEditRow(ViewModel1 viewModel)

As mentioned below, I'd rather the custom binder fired prior to executing the controller code instead of calling TryUpdateModel().


Solution

  • Try this:

    var viewModel = new ViewModel1();
    UpdateModel(viewModel.NestedType);