I have an action method without parameters.
The QueryString
collection contain all of my values. The keys of the QueryString
match my view model properties.
var queryStringValueProvider = new QueryStringValueProvider(ControllerContext);
var providerResult = queryStringValueProvider.GetValue(ValidationKeys.Id); // ?!
var viewModelTypeName = queryString[ValidationKeys.ViewModelType];
var viewModelType = Type.GetType(viewModelTypeName);
var viewModelInstance = providerResult.ConvertTo(viewModelType); // throws an InvalidOperationException
How can I convert the QueryString
collection to a view model?
ASP.NET MVC already do this when you just pass the view model into the action method parameters. So what I need is an afterwards model binding using ASP.NET MVC mechanics.
To manually do custom model binding, create a custom model binder (implement
IModelBinder
) and register it with your IoC container.Or you could call
this.UpdateModel
on inside your action method. This should bind the values from your ValueProvider (RouteData, Request.Form collection and QueryString) to your model.You could use
TryUpdateModel
My Controller Action
UpdateModel
The problem was that
UpdateModel
orTryUpdateModel
does not work forobject
by design. Both methods usetypeof(TModel)
. But you have to usemodel.GetType()
.Take a look at: Model Binding - Type in External Assembly
Darin Dimitrov gave the right answer :)
What you're asking for is serialization. For doing this simply, you could put a constructor overload that accepts a QueryStringValueProvider as an argument and that constructor is responsible initializing all of the model's properties based on the provider. If you stick to strings, you could very easily put such a constructor into a model base class that could be inherited by all of your models.
This could also be built into an extension method so it could be called "on demand" rather than at construction.