I used custom mvc route handler. But When I use Html.BeginForm or Ajax.BeginForm in the view, Action parameters change unexpectedly. My codes are above
My Register Route method is :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("alias",
"{alias}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
).RouteHandler = new FriendlyUrlRoutehandler();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
}
My MvcRouteHandler is :
public class FriendlyUrlRoutehandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var friendlyUrl = (string)requestContext.RouteData.Values["alias"];
if (friendlyUrl != null)
{
if (friendlyUrl.Equals("man-parfume"))
{
requestContext.RouteData.Values["controller"] = "ManParfume";
requestContext.RouteData.Values["action"] = "Index";
}
else if (friendlyUrl.Equals("ring"))
{
requestContext.RouteData.Values["controller"] = "Ring";
requestContext.RouteData.Values["action"] = "Index";
}
else if (friendlyUrl.Equals("glases"))
{
requestContext.RouteData.Values["controller"] = "Categories";
requestContext.RouteData.Values["action"] = "Index";
requestContext.RouteData.Values["id"] = 10;
}
}
return base.GetHttpHandler(requestContext);
}
}
My View is :
@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "Post" }))
@using (Html.BeginForm("Index", "Home"))
Finally wrong action in browser looks like this :
form action="/man-parfume" data-ajax="true" data-ajax-method="Post" id="form0" method="post"> form action="/man-parfume" method="post"> input type="submit" value="send" />
I wrote controller as a home in begin form but it changed when Html.BeginForm rendered.
How can I post the form to Home/Index?
You may use <form action="@Url.RouteUrl("Default", new { controller="Home", action="Index"}" method="post">
instead Html.BeginForm
.
As to Ajax.BeginForm
it may be changed on jQuery function:
$.ajax({
type: "POST",
url: "@Url.RouteUrl("Default", new { controller="Home", action="Index"}",
data: data,
success: success,
dataType: dataType
});