AT-2017
AT-2017

Reputation: 3149

Custom Route Doesn't Get The Query String

I am trying to do a simple routing as follows:

http://localhost:PortNo/Exam/2

So in the route config file, I've this:

routes.MapRoute(
        name: "Exam",
        url: "Exam/{id}",
        defaults: new { controller = "Exam", action = "Index" },
        namespaces: new[] { "App.Web.Controllers" }
);

In the controller:

 [HttpGet]
 public ActionResult Index(int id)
 {
    return View(GetQuestions(id));
 }

Unfortunately the above routing doesn't get me the query string value but this helps that I don't prefer:

ttp://localhost:PortNo/Exam/Index/2

Just wasted an hour for this simple thing, anything skipped here? Would appreciate an idea to overcome this.

Upvotes: 0

Views: 42

Answers (2)

David Liang
David Liang

Reputation: 21476

I don't see anything wrong with your route mapping, unless you have some other route configs you didn't show that conflict with this one:

routes.MapRoute(
    name: "Exam",
    url: "Exam/{id}",
    defaults: new { controller = "Exam", action = "Index" },
    namespaces: new[] { "App.Web.Controllers" }
);

This would correctly map the request http://localhost:PortNo/Exam/2 to the exam controller, index method and set the parameter ID = 2:

enter image description here

Upvotes: 1

Md Rahatur Rahman
Md Rahatur Rahman

Reputation: 3244

Please note that 2 is not a query string in the Url http://localhost:PortNo/Exam/2. It is the part of the Url. If you had written http://localhost:PortNo/Exam?id=2 then 2 would be a query string.

Assuming your route to action is working then change the route to:

routes.MapRoute(
     name: "Exam",
     url: "Exam/{id}",
     defaults: new { controller = "Exam", action = "Index", id = UrlParameter.Optional },
     namespaces: new[] { "App.Web.Controllers" }
);

Also since your id parameter is optional you should have is as a nullable int instead of an int like this:

 [HttpGet]
 public ActionResult Index(int? id)
 {
    return View(GetQuestions(id.value));
 }

Then you can also check conditions like if(id.hasvalue). Do not have to worry about the zero (0) value.

Upvotes: 1

Related Questions