0

I'm trying to understand the behavior within my RouteConfig setup. Here is what I have:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "2KeywordController",
            url: "{keyword1}-{keyword2}-{controller}/{action}",
            defaults: new { action = "Index" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}",
            defaults: new { controller = "Home", action = "Index" }
        );
    }
}

I have a controller called ContactController and a View under /Views/Contact/Index.cshtml that has the following to create the form:

@using (Html.BeginForm("Index", "contact", FormMethod.Post, new { id = "contactform" }))

When I navigate to example.com/kw1-kw2-contact the ContactController is correctly called and the default contact view is displayed. When I looked at the source I was surprised to find that the action for the form was set to "/kw1-kw2-contact" instead of just "/contact". Is there a way to use Html.Begin() but have just the controller name appear in action without the two keywords? e.g. /contact

1 Answer 1

3

Is there a way to use Html.Begin() but have just the controller name appear in action without the two keywords?

Sure, you could use a BeginRouteForm instead of a BeginForm and specify the route name you want to use:

@using (Html.BeginRouteForm(
    routeName: "Default", 
    routeValues: new { action = "index", controller = "contact" }, 
    method: FormMethod.Post, 
    htmlAttributes: new { id = "contactform" })
)
{
    ...
}

will emit:

<form action="/contact" id="contactform" method="post">
    ...
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

So BeginForm will use the last route and BeginRouteForm allows you to define the action? Thanks.
@Josh, precisely right. Actually small rectification: BeginForm will use the first route that matches the request. Routes are evaluated in the order you defined them. With BeginRouteForm you could explicitly specify the route you want to be used by his name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.