使用onchange重定向到另一个控制器

redirecting to another controller with onchange

本文关键字:另一个 控制器 重定向 onchange 使用      更新时间:2023-09-26
<th>@Html.DropDownList("Tables", new List<SelectListItem>
{
    new SelectListItem { Text = "A", Value = "Admin/Index"},
    new SelectListItem { Text = "B", Value = "Admin/Index"}
}, "WWW",new { @onchange="location=this.value" })</th>

此代码仅第 1 次有效,稍后重定向到控制器"管理员/索引",它开始自行复制。所以我有这样的地址

localhost/Admin/Admin/Index instead of localhost/Admin/Index

我也试过,但效果相同

@onchange="document.href.location=this.value
@onchange="window.href.location=this.value

如何制作正确的js,因此重定向将一直有效。

您需要使用绝对路径而不是相对路径。 我建议在重定向URL前面添加/,如下所示:

new { @onchange="location='/' + this.value" })

这种方法的唯一问题是,如果您曾经部署到应用程序不在根目录的服务器(例如,如http://myserver/myapp/Admin/Index(,则链接将不正确(即,它将指向http://myserver/Admin/Index(。 因此,最好使用 Url.Action 帮助程序:

@Html.DropDownList("Tables", new List<SelectListItem>
{
    new SelectListItem { Text = "A", Value = Url.Action("Index", "Admin") },
    new SelectListItem { Text = "B", Value = Url.Action("Index", "Admin") }
}, "WWW",new { @onchange="location=this.value" })

无论环境如何,这将确保正确的 URL。

您可以为值添加斜杠,使其始终从根开始:

<th>@Html.DropDownList("Tables", new List<SelectListItem>
{
    new SelectListItem { Text = "A", Value = "/Admin/Index"},
    new SelectListItem { Text = "B", Value = "/Admin/Index"}
}, "WWW",new { @onchange="location=this.value" })</th>