Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind URL parameters to model properties with different names

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.

like image 448
Polaris878 Avatar asked Dec 14 '11 16:12

Polaris878


People also ask

How do you assign parameters to a URL?

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.

What is modal binding?

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.


1 Answers

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.


If you can change the Bar class you can use this attribute:
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;
}
like image 157
Max Toro Avatar answered Oct 11 '22 05:10

Max Toro