Stack Overflow Asked by AT-2017 on November 12, 2021
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.
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:
Answered by David Liang on November 12, 2021
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.
Answered by Rahatur on November 12, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP