BeginForm不同的URL模式

BeginForm不同的URL模式

本文介绍了MVC Html.BeginForm不同的URL模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个表像这样的下拉:

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:

/站/视图?ID = f2cecc62-7c8c-498d-b6b6-60d48a862c1c

我要的是:

/站/查看/ f2cecc62-7c8c-498d-b6b6-60d48a862c1c

那么,如何获得ID =被更简单的URL方案我想换成查询参数?

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

推荐答案

与表单 FormMethod.Get 总会回来后的表单控件作为查询字符串值的值。浏览器无法生成一个URL根据您的路由配置,因为他们是服务器端code。

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.

如果你真的想要产生 /站/查看/ f2cecc62-7c8c-498d-b6b6-60d48a862c1c ,那么你可以使用JavaScript / jQuery来建立自己的网址,重定向

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();
});

边注:提交的 .change预计不会()事件的行为,是混乱给用户。推荐你添加一个按钮,让用户作出选择,检查,然后提交表单(手柄按钮的。点击()事件,而该DropDownList的 .change()事件)

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)

这篇关于MVC Html.BeginForm不同的URL模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:06