mvc Html.BeginForm 不同的 URL 架构

mvc Html.BeginForm different URL schema(mvc Html.BeginForm 不同的 URL 架构)
本文介绍了mvc Html.BeginForm 不同的 URL 架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在为 DropDown 创建一个表单,如下所示:

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

如果我从下拉列表中选择一个值,我会被重定向到正确的控制器,但 URL 不是我想要的:

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

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

我想要的是:

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

/Stations/View/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,因为它们是服务器端代码.

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.

如果您真的想生成 /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c,那么您可以使用 javascript/jquery 构建自己的 url 并重定向

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() 事件上提交不是预期的行为,并且会使用户感到困惑.建议您添加一个按钮让用户进行选择,检查它然后提交表单(处理按钮的 .click() 事件而不是下拉列表的 .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 架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

MSBuild cannot find a reference(MSBuild 找不到参考)
The reference assemblies for framework .NETCore, Version=v5.0 were not found(未找到框架 .NETCore,Version=v5.0 的参考程序集)
quot;File has a different computed hash than specified in manifestquot; error when signing the EXE(“文件的计算哈希值与清单中指定的不同签署EXE时出错)
MS-Build BeforeBuild not firing(MS-Build BeforeBuild 未触发)
Using C# 7.1 with MSBuild(将 C# 7.1 与 MSBuild 结合使用)
Build project with Microsoft.Build API(使用 Microsoft.Build API 构建项目)