Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not map a route for a specific controller in mvc 4

I have a controller named Registration and an action method in it as the following:

public JsonResult GetReqs(GridSettings gridSettings, int rt)
    {
        ...//whatever

        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

So I added a route and now my RouteConfig.cs is like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "RegReq",
            url: "{Registration}/{GetReqs}/{rt}",
            defaults: new { controller = "Registration", action = "GetReqs", rt = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );            
    }
}

However I can't access the rt parameter and the action method GetReqs isn't called(I set a breakpoint on it but nothing happened). Where is the mistake?

Edit: Link example I tried : ~/Registration/GetReqs/1

like image 591
Amin Saqi Avatar asked Jun 01 '13 11:06

Amin Saqi


People also ask

Which is the correct default route mapping within MVC?

The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. The Default route maps this URL to the following parameters: controller = Home. action = Index.

What is right way to define routes MapRoute () in MVC?

Routing in ASP.NET MVC cs file in App_Start Folder, You can define Routes in that file, By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional).

How many routes can be defined in the MVC application?

You can create as many route as you want in your RouteConfig. cs file.

Can you enable attribute routing in MVC?

Enabling Attribute Routing in ASP.NET MVC Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes. MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig. cs file. You can also combine attribute routing with convention-based routing.


1 Answers

I think you need to remove the brackets in your first route:

routes.MapRoute(
            name: "RegReq",
            url: "Registration/GetReqs/{rt}",
            defaults: new { controller = "Registration", action = "GetReqs", 
              rt = UrlParameter.Optional }
        );

The default route has {controller} to tell MVC to use the string in that section of the url as the controller name. You know the controller, so you just need to match the specific string.

like image 89
JeffB Avatar answered Nov 15 '22 03:11

JeffB