Phiter Fernandes Phiter Fernandes - 1 year ago 98
ASP.NET (C#) Question

Get third parameter in MVC

I have a MVC website, and I have this url:


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


I'll then get it in my code using

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


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:

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
that use the same View sending different values to the

Answer Source

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".

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:

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download