简体   繁体   中英

Custom ModelBinder with nested viewmodels

I have the following viewmodels:

public class ViewModel1{
    public string Foo{get;set;}
}

public class ViewModel2{
     public ViewModel1 Bar{get;set;}
}

And the following controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ViewModel2();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(ViewModel2 model)
    {
        return View(model);
    }
}

And I have a custom model binder configured as:

 ModelBinders.Binders.Add(typeof(ViewModel1), new ViewModel1ModelBinder());

However - the binder never gets called. Is this because it is nested? is the framework clever enough to see there is a child viewmodel of the required type to match this binder?

[edit]

here is the code for the model binder (though it never reaches this point):

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");
            string typeAndNS = modelType.Namespace + "." + typeValue.AttemptedValue;
            var type = Type.GetType(typeAndNS, true);
            var model = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
            return model;
        }

w://

This should work, at least it does work for me. I've taken the exact same code you have shown. The only thing that you haven't shown is the view.

So I've tested with the following:

~/Views/Home/Index.cshtml :

@model ViewModel2
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Bar)
    <input type="submit" value="OK" />
}

and the editor template ( ~/Views/Home/EditorTemplates/ViewModel1.cshtml ):

@model ViewModel1
@Html.Hidden("TableInputModelTypeName", "foobar")
@Html.EditorFor(x => x.Foo)

When I submitted the form the custom model binder was hit as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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