how to get Razor form to use route

2019-07-31 17:51发布

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

1条回答
倾城 Initia
2楼-- · 2019-07-31 18:08

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.

查看更多
登录 后发表回答