I have a controller method in ASP.NET MVC that looks like this:
public ActionResult GetAlbumPictures(int albumId)
{
var album = AlbumRepo.GetSingle(albumId);
var pictures = album.Pictures;
return View(pictures);
}
The routing for this method looks like this:
routes.MapRoute(null,
"pictures"
new { controller = "Album", action = "GetAlbumPictures" });
The user will use the following URL to get the pictures, filtered by the album ID:
GET http://server/pictures?albumid=10
However, I'd like to change the querystring parameter to just album
instead of albumid
:
GET http://server/pictures?album=10
This would mean that the controller method needs to be modified to:
public ActionResult GetPictures(int album)
{
...
}
However, this is not ideal because now the method has a parameter named album
, which can be confused as an Album
object instead of the ID
of the Album
.
My question is, is there any way of configuring ASP.NET MVC so that in the routing, it will receive a querystring parameter called album
, but then pass it off to the controller as the albumId
parameter?
P.S. I know that I can do this in the routing table:
routes.MapRoute(null,
"album/{albumId}/pictures",
new { controller = "Album", action = "GetAlbumPictures" });
But due to legacy issues, I have to make it work for the querystring method as well.
The QueryString collection is used to retrieve the variable values in the HTTP query string. The line above generates a variable named txt with the value "this is a query string test". Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.
As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.
You can create a custom action filter attribute to handle this scenario. I haven't tested this specific implementation, but the general idea is to do something like this:
public class AlbumAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var albumId = filterContext.HttpContext.Request.QueryString["album"] as string;
filterContext.ActionParameters["albumId"] = albumId;
base.OnActionExecuting(filterContext);
}
}
Then, decorate your action method with the [Album] attribute:
[Album]
public ActionResult GetAlbumPictures(int albumId)
{
var album = AlbumRepo.GetSingle(albumId);
var pictures = album.Pictures;
return View(pictures);
}
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