MPelletier
MPelletier

Reputation: 16697

ASP.NET MVC changes route elements, want them back as original route, not params

This is purely for aesthetics but...

My base url has two parameters:

https://localhost:44360/Appointment/Index/Os12RB/john-doe

But doing a post from this form:

@using (Html.BeginForm("Index", "Appointment", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.UniqueId)
    @Html.HiddenFor(model => model.Name)
    @Html.HiddenFor(model => model.SelectedDate)
}

Returns to the url: https://localhost:44360/Appointment/Index

I actually want to keep it with the two parameters in the route like the original (https://localhost:44360/Appointment/Index/Os12RB/john-doe) after posting.

Route mapping:

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

How do I keep the route intact?

Upvotes: 0

Views: 45

Answers (1)

CarenRose
CarenRose

Reputation: 1316

I was originally mistaken about how the routeValues would work.

Instead of using the Html.BeginForm method, you should instead use the Html.BeginRouteForm method.

This method takes the route name, route values, and the form method. In the route values you pass, you'll need to include values for the controller and action as well.

@using (Html.BeginRouteForm("Appointment_Index",
            new { controller = "Appointment", action = "Index", uniqueId = model.UniqueId, name = model.Name },
            FormMethod.Post))
{
    // ...
}

Original answer below:

There's an overload of `Html.BeginForm` which takes a `routeValues` object.

So you could do this:

@using (Html.BeginForm("Index", "Appointment",
            new { uniqueId = model.UniqueId, name = model.Name },
            FormMethod.Post))
{
    // ...
}

I believe that would accomplish what you're wanting.

Upvotes: 0

Related Questions