In asp.net mvc3 I want to have a generic method which adds a viewmodel object to the database from wherever it is sent to the right spot in the database. To do this, I am trying to pass in the posted model. However, I am having a little difficulty doing it dynamically. I tried this but it didn’t work:
view:
(psuedo)
begin form aiming at Add
fields
input type = submit
controller action
[HttpPost]
public ActionResult Add(dynamic model,...)
The issue is that model is never filled. The hidden fields are, but the actual fields defined by the model with the helpers are not going into model. I realize that just naming it model is more than likely not going to line up right. I am sure if I strongly typed the model, such as (MyExplicitClass model,...) it would work but that defeats the dynamic approach because I want to be able to send class1, class2, class3, class5, class8, class13, etc.
Is there any way to get this working in that no matter what @model class21 is sent, the dynamic model (or equiv) will capture that object?
No. At least not without using a custom model binder.
You have a fundamental misunderstanding of how model binding works. You think that model binding works based on the @model in the view. This couldn’t be further from the truth. Model binding works by looking at the parameters specified in the action method.
All the model binder does is look at the type of the parameters specified for the action method, and then look at the Request values (either querystring or post) and try to match them up. If it finds a match, it instantiates the object.
The key here is that the model binder only instantiates the objects specified in the parameters of the action method. What object is “dynamic”? It has no idea. Therefore it can’t create any type.
EDIT:
You may find this question useful
Polymorphic model binding