asp mvc 5 Attribute routing not firing - asp.net-mvc

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")]

Related

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"

How to display only name in url instead of id in mvc.net using routing

I am getting url like http://localhost:49671/TestRoutes/Display?f=hi&i=2
I want it like http://localhost:49671/TestRoutes/Display/hi
I call it from Index method.
[HttpPost]
public ActionResult Index(int? e )
{
// return View("Display", new { f = "hi", i = 2 });
return RedirectToAction("Display", new { f = "hi", i = 2 });
}
Index view
#model Try.Models.TestRoutes
#using (Html.BeginForm())
{
Model.e = 5 ;
<input type="submit" value="Create" class="btn btn-default" />
}
Display Action method
// [Route("TestRoutes/{s}")]
public ActionResult Display(string s, int i)
{
return View();
}
Route config file
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
});
You need to change your route definition to
routes.MapRoute(
name: "Professional",
url: "TestRoutes/Display/{s}/{i}",
default: new { controller = "TestRoutes", action = "Display", i = UrlParameter.Optional }
);
so that the names of the placeholders match the names of the parameters in your method. Note also that only the last parameter can be marked as UrlParameter.Optional (otherwise the RoutingEngine cannot match up the segments and the values will be added as query string parameters, not route values)
Then you need to change the controller method to match the route/method parameters
[HttpPost]
public ActionResult Index(int? e )
{
return RedirectToAction("Display", new { s = "hi", i = 2 }); // s not f
}
change your route as
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{name}", // URL with parameters
new
{
controller = "TestRoutes",
action = "Display"
} // Parameter defaults
);
and your action as
public ActionResult Display(string name)
{
//action goes here
}
Remove the maproute code:
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
Use attribute routing code:
[Route("TestRoutes/{s}/{i?}")]
public ActionResult Display(string s, int? i)
{
return View();
}
You can also try using Attribute Routing. You can control your routes easier with attribute routing.
Firstly change your RouteConfig.cs like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
}
After that change your controller files like that:
namespace YourProjectName.Controllers
{
[RoutePrefix("Home")]
[Route("{action}/{id=0}")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("ChangeAddress/{addressID}")]
public ActionResult ChangeAddress(int addressID)
{
//your codes to change address
}
}
You can also learn more about Attribute Routing in this post:
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
Another way to solve this problem is to put the proper route before the default route, as follows:
routes.MapRoute(name: "MyRouteName", url: "Id", defaults: new { controller= "Home", action = "Index",id= Id });
Default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{Id}",
defaults: new { controller = "Home", action = "Index",id= Id }
);

UrlParameter.Optional not working in Razor

I am using below code in layout for links:
But it's not working, here is my route Config
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 }
);
}
This is my NewProduct Controller:
public ActionResult NewProduct(int id = -1)
{
NewProductModel m = new NewProductModel();
return View(m);
}
What is problem in my UrlParameter.optional
When you using #Url.Action helper you should pass the actual value to parameter like this:
#Url.Action("NewProduct", "Administrator", new { id = 1 })
UrlParameter.Optional should be used only in RouteConfig as you see in your code.
in NewProduct controller :
public ActionResult NewProduct(int id = -1)
{
NewProductModel m = new NewProductModel();
m.Id = id;
return View(m);
}
and for Link

mvc 4 url custom routing issue

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

User routing in ASP.NET MVC for urls like www.website.com/users/jeffAtwood

I am trying to show user details at the following url :
www.website.com/users/yasser
where the last entry yasser is the username I have tried a couple of routes but it just does nt work.
My User controller is as shown below.
public class UserController : Controller
{
public ActionResult Index(string username)
{
var model = _service.GetUserDetails(username);
return View(model);
}
}
I have reffered this and couple of other links, but I really could not figure out how it worked.
Can some one help me out on this. Thanks
Edit :
My current route config is below
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 executes from top to the bottom:
routes.MapRoute("UserProfile",
"Users/{username}",
new { controller = "User", action = "Index", username = string.Empty }
);
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);

Resources