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?

1
  • To enable attribute routing, call MapMvcAttributeRoutes during configuration. Commented Oct 14, 2015 at 7:18

2 Answers 2

4

Have you enabled attribute routing by adding this line:

routes.MapMvcAttributeRoutes(); 

in RegisterRoutes?

Sign up to request clarification or add additional context in comments.

Comments

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 } ); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.