Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual model binding with .Net Mvc

I'm wondering if there is a way to use the built in model binding similar to the internal model binding that occurs before a controller action.

My problem is that I want to be able to control the binding as I won't know the type of object to bind until I'm actually in the context of the controller action.

I understand I can inherit the DefaultModelBinder to perform custom binding, but I'm happy with what's already on offer, and just want to utilise it - take this ideal example to get an idea of what I'm after:

public ActionResult DoCustomBinding(string modelType)
{
    ... // logic to determine type to check and create strong 'actual' type

    object model = BindModel(actualType);

    ... // do something with bound model

    return View();
}

I've looked into using the DefaultModelProvider but unsure if this is the right way of going about this and I wasn't sure how to obtain the ModelBindingContext.

like image 787
Phil Cooper Avatar asked Apr 04 '12 20:04

Phil Cooper


People also ask

How do you bind a model to view in MVC?

Step 1: Open the VS 2019 and select the ASP.NET core web application. Step 2: Select the template of the web application (MVC). Step 3: Go to the home controller and student basic type binding. Step 5: Now, press f5 and run the solution.

Does MVC use data binding?

MVC doesn't use data bindings like old web api. You have to use model bindings in a MVC or MVVM approach.


1 Answers

If anyone comes across this question from google as I did here is the answer: How to gain control over model binding?

In short: TryUpdateModel is the method you are looking for.

like image 168
Kugel Avatar answered Sep 21 '22 04:09

Kugel