Using MVC3 is there a better way of removing previous routing values and also stopping them being used as a query string?
After much searching in finding a way of stopping MVC3 from reusing existing route values when generating a URL i have the following:
In Global.asax.cs:
routes.MapRoute("justAction", "{controller}/{action}", new { controller = "Home", action = "Index",id = "NONE",id2 = "NONE" });
routes.MapRoute("justID", "{controller}/{action}/{id}/{id2}", new { controller = "Home", action = "Index" });
routes.MapRoute("idAndId2", "{controller}/{action}/{id}", new { controller = "Home", action = "Index" });
And my page Index.cshtml
@Html.ActionLink("Index with id = 10", "Index", new { id = 10 }, null);
@Html.ActionLink开发者_如何学C("Index with id2 = 11", "Index", new { id = 0, id2 = 11 }, null);
@Html.ActionLink("Index", "Index", new { id = "NONE",id2= "NONE" },null); //Gives a URL of "/" with the existing route values removed
My problem is this seems to be a messy way of doing it and I am sure there must be a better method. As I would have to ensure that "NONE" was never possible for id or id2. As it seems like there could be a danger of accidentally using the "justAction" route.
Is there a better way, using MVC3 for removing existing route values and also stopping them appearing as a url query string?
Strictly speaking, you could use a constraint to prevent the use of "NONE"
:
routes.MapRoute("justID",
"{controller}/{action}/{id}/{id2}",
new { controller = "Home", action = "Index" },
new { id = new NotNoneConstraint(), id2 = new NotNoneConstraint());
And create the NotNoneConstraint
class:
public class NotNoneConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
return values.ContainsKey(parameterName) &&
values[parameterName] != "NONE";
}
}
That would effectively prevent routes from matching when the parameter is equal to "NONE"
. Parameters with NotNoneConstraint
would also become mandatory for the route to match a given URL.
Now, if your id arguments are numeric only, it would be far more elegant and simple to use a regular expression for the constraint:
routes.MapRoute("justID",
"{controller}/{action}/{id}/{id2}",
new { controller = "Home", action = "Index" },
new { id = @"\d+", id2 = @"\d+");
精彩评论