0

Most likely a very basic question, but still: In an ASP.Net MVC application, how can I enable a controller to respond to URLs that have either named or unnamed URL parameters.

With the following controller:

[Route("test/display/{scaleid}")]
public ActionResult Display(int scaleid)
{
    return View();
}

I try two URL requests - the first one works, the second one (where I specify the parameter name), doesn't work. Why is this?

http://localhost:43524/Test/Display/11
http://localhost:43524/Test/Display/?scaleid=11
Proposition Joe
  • 481
  • 4
  • 8
  • 22
  • Configure Routes in Route COnfig file http://stackoverflow.com/questions/2246481/routing-with-multiple-parameters-using-asp-net-mvc – Sreejith Jun 29 '15 at 06:47

3 Answers3

2

The last slash in

localhost:43524/Test/Display/?scaleid=11

will break the routing for that URL. This should resolve:

localhost:43524/Test/Display?scaleid=11 
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • Unfortunately, I still get an error when taking out the last slash and trying the suggested URL. "Resource not found" for "/Test/Display" – Proposition Joe Jun 29 '15 at 11:06
1

Because you told ASP, that the URL mapping is "test/display/scaleid". So in your second test "scaleid" is not defined.

I can not test it at the moment but please try this mapping: "test/display/{scaleid}?{scaleid}

DavidVollmers
  • 677
  • 5
  • 17
1

1) Make parameter optional:

[Route("test/display/{scaleid:int?}")]
public ActionResult Display(int scaleid? = Nothing)
{
    return View();
}

2) If url parameter is missing, try to take it from query string:

   string scaleid_par = this.Request.QueryString["scaleid"];
   if (!scaleid.HasValue && !string.IsNullOrEmpty(scaleid_par) ) {
        int.TryParse( scaleid_par, scaleid );
   }
dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • Thanks - when I add "{scaleid:int?}" to the route, then it works. Why is this? Why can I use a named parameter in the URL when I introduce a type constraint on the route, and make it optional? – Proposition Joe Jun 29 '15 at 12:29
  • Not type needed to fix your code, just set it as optional/nullable (? char). Glad to help. – dani herrera Jun 29 '15 at 12:32