1

I have a Razor form

using (Html.BeginForm("TermList", "Course", FormMethod.Get))
{

    <div style="text-align:right;display:inline-block; width:48%; margin-right:25px;">
             @Html.DropDownList( "id", (SelectList) ViewBag.schoolId)
    </div>
    <input type="submit" value="Choose school" />
}

I expected this form to post to URI of:

http://localhost:56939/Course/TermList/764

instead the route looks like:

http://localhost:56939/Course/TermList?id=764

the route is not being used. I'd like to do away with the parameter

?id=764
Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
  • I've just solved this problem with a simple redirect http://stackoverflow.com/a/18105353/360211 – weston Aug 07 '13 at 14:10

1 Answers1

1

The reason ?id=764 is appended to the URL is because you're using FormMethod.Get. Any values you are going to pass along with your form will be added in the querystring. You need to use FormMethod.Post.

@using(Html.BeginForm("TermList", "Course", FormMethod.Post))
{
    ... Your form stuff here ...
}

This will result in a form action of http://localhost:56939/Course/TermList/

If you want to post to http://localhost:56939/Course/TermList/764 you need to pass the id parameter in the Html.BeginForm statement:

@using(Html.BeginForm("TermList", "Course", new { @id = 764 }, FormMethod.Post))
{
    ... Your form stuff here ...
}

Obviously instead of hard coding 764 just use whatever variable it is that stores that value.

HTX9
  • 1,717
  • 3
  • 15
  • 27
  • why use post ? `http://localhost:56939/Course/TermList/764` can be achieved with a GET – Yasser Shaikh Dec 22 '12 at 05:26
  • Ok, I appreciate your point, but the value selected will come from a dropdown. The dropdown value won't be selected at render time. – Dave Alperovich Dec 22 '12 at 18:01
  • @DaveA Do you want the route to be `http://localhost:56939/Course/TermList/` or `http://localhost:56939/Course/TermList/764`? If you want the first route, the first solution I posted should still work as long as the dropdown has the name `id`. For the second route, I can update my answer to show how to do it with the value rom the dropdown. – HTX9 Dec 22 '12 at 18:12
  • the 2nd. I'd like it to be restfull. So i want to use get over post and the url should appear http://localhost:56939/Course/TermList/764. That's what I expected to get. I would appreciate any help getting to that point. Thanks again. – Dave Alperovich Dec 22 '12 at 18:21
  • Unfortunately there isn't any real way to do it through the `Html.BeginForm()` helper simply because the browser will always render it as a querystring. You would have to use jQuery to alter the URL after the HTML is rendered. See http://stackoverflow.com/questions/891603/html-beginform-loses-routevalues-with-formmethod-get and http://stackoverflow.com/questions/1574181/asp-net-mvc-rewritting-formmethod-get-querystring – HTX9 Dec 22 '12 at 19:09