Phiter Fernandes Phiter Fernandes - 15 days ago 7
ASP.NET (C#) Question

Get third parameter in asp.net MVC

I have a asp.net MVC website, and I have this url:

Home/Index/


There is one action that I want to do, and currently I'm doing it using query string, like this:

Home/Index/?action=1


I'll then get it in my code using
Request.QueryString["action"]
.

But this does not look as good as it should, I'd like to have something like this:

Home/Index/Action


So the query string would be a third parameter. How can I use it like this and check if the third parameter exists, and it's name?

My routes are configured like this:

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


Do I need to change anything on the routes or I can just enter the way I want, and if so, how do I retrieve this value?




Edit :

Alright. What I wanted to do was to have a different result in the view depending on this parameter.

What I did now was create two
ActionResults
that use the same View sending different values to the
ViewData
.

Answer

In MVC there is the concept of Model Binding, where the names of the parameters are used and then filled with values from the Form, without you having to do it.

If you write your Action method like this:

public ActionResult Index(int action)
{ ... }

then it will already work for /Home/Index?action=1.

If you want to be able to call it like /Home/Index/1 then the easiest way is to simply write the Action method like this:

public ActionResult Index(int id)
{ ... }

This works because the MapRoute definition basically says 'if there is something after the {action} part (which in this case is "Index", by the way), then give it the parameter name {id} and bind it to the {id} parameter of my Action method".


Update:
The problem with using a parameter called action in both calling scenarios is that {action} is a special keyword in MVC.
To use MySpecialParam for both calling scenarios, you could just add this Route:

routes.MapRoute(
    name: "Default_MySpecialParam",
    url: "{controller}/{action}/{MySpecialParam}",
    defaults: new { controller = "Home", action = "Index", MySpecialParam = UrlParameter.Optional }
);

However if MySpecialParam were to become action, then there is a name resolution conflict that MVC probably won't know how to handle, or it may even throw an error.