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
1

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, I still get an error when taking out the last slash and trying the suggested URL. "Resource not found" for "/Test/Display"
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 );
   }

2 Comments

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?
Not type needed to fix your code, just set it as optional/nullable (? char). Glad to help.
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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.