c# - Routing wrong access the action -
by default url routing in mvc {controller}/{action}/{id}. can access mydomain.com/products/details/1 , etc.
now, have register map route called categorylandingpage.
routes.maproute( name: "categorylandingpage", url: "category", defaults: new { controller = "category", action = "index" });
so show category in page.
then register map route called categorydetails
routes.maproute( name: "categorydetails", url: "category/{categoryname}", defaults: new { controller = "category", action = "details", categoryname = urlparameter.optional });
when access mydomain.com/category/cars, show products related cars.
same controller have another actions such create,edit,delete, , more.
the problems is,when access mydomain.com/category/create go details action. not go create action in category contoller.
how can solved matter?
two ways:
either use route constraint ensure {categoryname} part match 1 of categories:
//you have make var categoryrouteconstraint = new categoryrouteconstraint(); routes.maproute( name: "categorydetails", url: "category/{categoryname}", constraints: new { categoryname = categoryrouteconstraint } defaults: new { controller = "category", action = "details", categoryname = urlparameter.optional });
example route constraint:
public class categoryrouteconstraint : irouteconstraint { public bool match(httpcontextbase httpcontext, route route, string parametername, routevaluedictionary values, routedirection routedirection) { if (routedirection == routedirection.urlgeneration) return true; if (string.equals(parametername, "categoryname", stringcomparison.ordinalignorecase)) { //return true if (string)values[parametername] == "known category name" } return false; } }
or, intercept specific actions first:
routes.maproute( name: "categorydetails", url: "category/create", defaults: new { controller = "category", action = "create", categoryname = urlparameter.optional }); routes.maproute( name: "categorydetails", url: "category/delete", defaults: new { controller = "category", action = "delete", categoryname = urlparameter.optional }); //do 1 edit, delete //categorydetails route after routes.maproute( name: "categorydetails", url: "category/{categoryname}", defaults: new { controller = "category", action = "details", categoryname = urlparameter.optional });
Comments
Post a Comment