Okay, lets say I have a URL like so, which is mapped via HTTP verb GET to the controller action I have below:
GET /foo/bar?sort=asc&r=true
How can I bind this to my model Bar on my controller action I have below:
class Bar {
string SortOrder { get; set; }
bool Random { get; set; }
}
public ActionResult FooBar(Bar bar) {
// Do something with bar
return null;
}
Note that the property names won’t and can’t necessarily match the names of the URL parameters. Also, these are OPTIONAL url parameters.
The model binder matches the parameters it gets from the view to the model you have in the action by the Names, so if they won’t match the binding will not work.
options you got:
so basically, You can’t do exactly what you want.
Update:
You wrote in a comment that the properties CAN match the parameters names, so instead of write custom attributes that maybe will succeeded to do the binding, just write a ViewModel (The VM fromMVC…) to adjust the url parameters names.
Writing custom model binder is not recommended by the MVC team: