I am trying to use Route Attributes to define the MVC Routing.
I have got the following code in the Controller..
[Route("MDT/Detail/{id}")]
public JsonResult Detail(int? id)
{
ITS.Models.ComputerDetail cp = GetDataFromDatabase(id.Value);
return Json(cp, JsonRequestBehavior.AllowGet);
}
If I used this URL (http://localhost:6481/MDT/Detail?id=1245) it returns JSON data.
But If I used (http://localhost:6481/MDT/Detail/1245), it shows the error saying the variable id is Null.
Exception Details: System.InvalidOperationException: Nullable object must have a value.
Could you please help me how I could achieve {Controller}/{Action}/{ID} routing by using Routing Attribute?
Please try below code, it might helpful for you,
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}