Patrick M
Patrick M

Reputation: 10989

Using HtmlHelper.BeginForm to match a complicated route

I have a complicated route that I would like to match with an HtmlHelper.BeginForm method. I've read quite a few articles and answers on using route value dictionaries and object initializers and html attributes. But they all fall short of what I want to do...

Here is the route I want to match:

// Attempt to consolidate all Profile controller actions into one route
routes.MapRoute(
    "Profile",
    "{adminUserCode}/{controller}s/{customerId}/{action}/{profileId}",
    new { adminUserCode = UrlParameter.Optional, controller = "Profile"},
    new { adminUserCode = @"\d+", customerId = @"\d+", profileId = @"\d+" }
);

An example url for the controller & action I want to match with this would be:

http://mysite.com/123/Profiles/456/UpdatePhoneNumber/789

With the actual phone number being in the POST body

And here is the closest syntax I've come to getting right:

@using (Html.BeginForm(
    "UpdatePhoneNumber",
    "Profile",
    new {
        customerId = Model.LeadProfile.CustomerId,
        profileId = Model.CustomerLeadProfileId
    }))
{
    <!-- the form -->
}

But this puts the parameters in the object as query string parameters, like this:

<form method="post"
    action="/mvc/123/Profiles/UpdatePhoneNumber?customerId=78293&profileId=1604750">

I just tried this syntax on a whim, but it output the same thing as the other overload

@using (Html.BeginForm(new
{
    controller = "Profile",
    customerId = Model.LeadProfile.CustomerId,
    action = "UpdatePhoneNumber",
    profileId = Model.CustomerLeadProfileId
}))

I know I can just fall back on raw HTML here, but there seems like there should be a way to get the silly HtmlHelper to match more than the most basic of routes.

Upvotes: 1

Views: 335

Answers (1)

nemesv
nemesv

Reputation: 139758

If you want to use complicated routes in your form you need to use the BeginRouteForm Method

@using (Html.BeginRouteForm("Profile", new
{
    controller = "Profile",
    customerId = Model.LeadProfile.CustomerId,
    action = "UpdatePhoneNumber",
    profileId = Model.CustomerLeadProfileId
}))

Upvotes: 1

Related Questions