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.
To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.
Model binding is a process in which we bind a model to controller and view. It is a simple way to map posted form values to a . NET Framework type and pass the type to an action method as a parameter. It acts as a converter because it can convert HTTP requests into objects that are passed to an action method.
It's not supported out of the box, but you could do this:
class BarQuery : Bar {
public string sort { get { return SortOrder; } set { SortOrder = value; } }
public bool r { get { return Random; } set { Random = value; } }
}
public ActionResult FooBar(BarQuery bar) {
// Do something with bar
}
You could implement a custom IModelBinder
, but it's much easier to do manual mapping.
class FromQueryAttribute : CustomModelBinderAttribute, IModelBinder {
public string Name { get; set; }
public FromQueryAttribute() { }
public FromQueryAttribute(string name) {
this.Name = name;
}
public override IModelBinder GetModelBinder() {
return this;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
return controllerContext.HttpContext.QueryString[this.Name ?? bindingContext.ModelName];
}
}
class Bar {
[FromQuery("sort")]
string SortOrder { get; set; }
[FromQuery("r")]
bool Random { get; set; }
}
public ActionResult FooBar(Bar bar) {
// Do something with bar
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With