1

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?

TTCG
  • 8,805
  • 31
  • 93
  • 141

2 Answers2

4

Have you enabled attribute routing by adding this line:

routes.MapMvcAttributeRoutes();

in RegisterRoutes?

Sk93
  • 3,676
  • 3
  • 37
  • 67
0

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 }
    );
}
Sanjay Bhardwaj
  • 412
  • 2
  • 10