I have an action that looks like this:
[Post]
[PopulateModelFromId]
public ActionResult ChangeName( string name, MyModel model )
{
try
{
model.changeName
return JSONSuccess();
}
catch( ModelUpdateException )
{
return JSONFail();
}
}
The name and model id are sent by an ajax POST, and the model is populated by a custom action filter that takes the id and retrieves the model from the database.
The actionfilter looks like this:
...
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// parse the id from the request
MyModel model = getModelFromDataStoreById( id );
filterContext.ActionParameters["model"] = model;
}
...
The problem is that the MyModel object doesn’t have a parameterless constructor, and MVC is attempting to create and bind to the MyModel object before the ActionFilter is even called but throws an exception because it cannot instantiate the MyModel object.
My first question is am I doing this properly or should I be using something like HttpContext.Items to transfer data between filter and action? Second, is there a way to tell MVC to not try to bind the MyModel object because it will be created later?
A custom model binder seems more appropriate for this task than a custom action filter:
which yuo would register in
Application_Start:Now your controller action might look like this: