Adding an alias to an action parameter for model binding in ASP.NET MVC

This is the introduction of a new Nuget package called ActionParameterAlias.

Have you ever had a URL:

http://example.com?productid=123456

where you wanted to bind it with an ASP.NET MVC action like this?

   1:  public ActionResult Search(Product product)
   2:  {
   3:      //...
   4:      return View(product);
   5:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Chris Missal was discussing this for a project, so we worked together and came up with an action filter that enables the use of aliases.  More specifically, the following allows the same action to accept url with a query string parameter matching it or any of the aliases.

   1:  [ParameterAlias("Product", "pid", Order = 1)]
   2:  [ParameterAlias("Product", "p_id", Order = 2)]
   3:  [ParameterAlias("Product", "productid", Order = 3)]
   4:  public ActionResult Search(Product product)
   5:  {
   6:      //...
   7:      return View(product);
   8:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Just head on over to Nuget and go grab it.  This is a feature that I’d like to see make it into the next version of the framework.  It’s so tiny of a feature, but so many folks have parameter names that are just a bit off because there is no way to add aliases currently.

CropperCapture[1]

To check out the code, clone it from BitBucket here: https://bitbucket.org/jeffreypalermo/action-parameter-alias or on the Nuget gallery at http://nuget.org/packages/ActionParameterAlias/4.0.0.