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

时间:2013-08-19 19:29:24

标签: javascript asp.net-mvc

<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>

此代码仅适用于第一次,后来改为重定向到控制器“管理员/索引”,它开始复制自己。所以我有这样的地址

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

我也试过,但效果相同

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

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

2 个答案:

答案 0 :(得分:2)

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

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。

答案 1 :(得分:1)

您可以为值添加斜杠,因此它始终从根目录开始:

<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>