mvc 4 url custom routing issue - asp.net-mvc

i have an action which takes two parameters but when action is called, parameters are displayed in the url as query string like this:
localhost:34795/Verification?DepartmentID=3&SubDepartmentID=2
I know that using custom url route i can change this to like this:
localhost:34795/Verification/3/2
but i am unable to do this i added this code to Globas.asax but no outcome till"
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Blog", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new { controller = "Verification", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//routes.MapRoute(
// "Default", // Route name
// "{controller}/{action}/{id}", // URL with parameters
// new { controller = "TestDetails", action = "GetSubDepartmentID", id = "" } // Parameter defaults
//);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
i did this way but nothing happened, what i am doing wrong?

This should do the trick:
routes.MapRoute("Blog",
"Verification/{DepartmentID}/{SubDepartmentID}",
new {
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
}
);
Then in your Index function in VerificationController:
public ActionResult Index(int DepartmentID, int SubDepartmentID)

I have got the solution, after thorough debugging i realized that in asp.net mvc 4 it creates some classes by default in application Shared directory and there for registering routes application was calling this method:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
You see here its calling RegisterRoutes method which is in RouteConfig.cs file which means in RouteConfig class its not calling the method of Global.asax, this was the issue and i got mad solving it and at last this result i got and got thing to work.
Here is my RouteConfig.cs code which solved the issue and make things work:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("home", "", new { controller = "Home", action = "Index" });
routes.MapRoute(
"Verification", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new
{
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Related

MVC parameter returning null value

Below is the Controller code:
public class HomeController : Controller
{
//
// GET: /Home/
public string Index(string name)
{
return "Welcome to MVC_Demo"+name;
}
}
and below is the Global.asax.cs codes:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
When I run the application and browse for (http://localhost/MVC_Demo/home/index/pradeep) it shows only,
"Welcome to MVC_Demo" as the output, and not as "Welcome to MVC_Demo Pradeep" i.e the parameter name "Pradeep" is not getting displayed.
Considering me just a beginner any help would be highly appreciated.
As your route states, the default parametername is id. So either change the default parametername to be name like this
routes.MapRoute(
"Default",
"{controller}/{action}/{name}",
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
Or you can change the name of the parameter to be id and match the route.
public string Index(string id)
{
return $"Welcome to MVC_Demo {id}";
}
One more solution is to specify the parametername explicitly as a QueryString parameter:
http://localhost/MVC_Demo/home/index?name=pradeep

MVC Handling a Blog Request / Description URL [duplicate]

I would like to create a dynamic routing to a URL like following:
http://localhost:51577/Item/AnyActionName/Id
Please note that the controller name is static and doesn't need to be dynamic. On the other hand, I need to have the action name part dynamic so that whatever is written in that part of URL, I would redirect the user to the Index action inside of Item controller.
What I have tried so far is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Items",
"Item/{action}/{id}",
new { controller = "Item", action = "Index", id = UrlParameter.Optional });
}
And when I build my app I get a following error:
The resource cannot be found.
Edit:
Here is my Global.asax file and the routeconfig.cs file:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
And here's the content of the RouteConfig.cs file with the answer that #Nkosi provided:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Items",
url: "Item/{id}/{*slug}",
defaults: new { controller = "Item", action = "Index", slug = UrlParameter.Optional }
);
}
}
What you are referring to in your question is called a slug.
I answered a similar question here for web api
Web api - how to route using slugs?
With the slug at the end the route config would look like this
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Items",
url: "Item/{id}/{*slug}",
defaults: new { controller = "Item", action = "Index", slug = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
which could match an example controller action...
public class ItemController : Controller {
public ActionResult Index(int id, string slug = null) {
//...
}
}
the example URL...
"Item/31223512/Any-Item-Name"
would then have the parameters matched as follows...
id = 31223512
slug = "Any-Item-Name"
And because the slug is optional, the above URL will still be matched to
"Item/31223512"

Url routing with static name mvc

I have a controller name Dashboard and inside that controller i have an action AdminDashboard . Now by default url of this action becomes /Dashboard/AdminDashboard . I want to map this action to this url /SupervisorDashboard
This is what i am doing but its saying not found
routes.MapRoute(
name: "SupervisorDashboard",
url: "SupervisorDashboard",
defaults: new { controller = "Dashboard", action = "AdminDashboard" }
);
and also how can i redirect to this page using Url.Action
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "SupervisorDashboard",
url: "SupervisorDashboard",
defaults: new { controller = "Dashboard", action = "AdminDashboard" }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Have you placed this new route definition before default route? Routes are evaluated in the same order in which they were registered. If you put default route before any of custom routes, it will be used (and since you probably don't have any SupervisorDashboardController in code, 404 will be returned).
Url.Action should work correctly, if routes are defined in correct order.
So, for this case, RouteConfig should look like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// this one match /SupervisorDashboard only
routes.MapRoute(
name: "SupervisorDashboard",
url: "SupervisorDashboard",
defaults: new { controller = "Dashboard", action = "AdminDashboard" }
);
// should be last, after any custom route definition
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

asp mvc 5 Attribute routing not firing

I'm trying to use the attribute routing in a new project, but I can't get it to work.
Here is what I have so far :
[RoutePrefix("Product")]
public class ProductController : Controller
{
[Route("{id}/{title}", Name = "Product Details")]
public ActionResult Index(int id = 0, string title = "")
{
Product p = Product.Get(id);
return View(p);
}
}
And here is my RouteConfig.cs :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// "Product Details",
// "Product/{id}/{title}",
// new { controller = "Product", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
//);
routes.MapRoute(
name: "DefaultIndex",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
If I remove the Routing attributes and uncomment the first route in my RouteConfig.cs it works fine, but I'd like to stick with route attributes.
Any idea why it's not working correctly ?
The URL I want to use is : http://www.mydomain.com/Product/12345/ProductName
EDIT, here is my Application_Start()
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleMobileConfig.RegisterBundles(BundleTable.Bundles);
}
Looks like its treating the {id} as an action.
Try this:
[Route("{id:int}/{title}", Name = "Product Details")]
Or this
[Route("Product/{id}/{title}", Name = "Product Details")]

Parameter value not passed in ASP.NET MVC route

I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.

Resources