mvc Html.BeginForm different URL schema

旧城冷巷雨未停 提交于 2019-11-26 10:01:47

问题


I\'m creating a form for a DropDown like this:

@{
    Html.BeginForm(\"View\", \"Stations\", FormMethod.Get);
}
@Html.DropDownList(\"id\", new SelectList(ViewBag.Stations, \"Id\", \"Name\"), new { onchange = \"this.form.submit();\" })
@{
    Html.EndForm();
}

If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:

/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c

What I want is:

/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c

So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?


回答1:


A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.

If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect

@using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
    @Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}

var baseUrl = '@Url.Action("View", "Stations")';
$('#id').change(function() {
    location.href = baseUrl + '/' $(this).val();
});

Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)




回答2:


Remove "id" from

@Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })


来源:https://stackoverflow.com/questions/37775445/mvc-html-beginform-different-url-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!