gpt4 book ai didi

javascript - 下拉菜单无缝地路由到不同的 Controller /操作方法

转载 作者:行者123 更新时间:2023-11-30 18:27:12 27 4
gpt4 key购买 nike

MVC 网站 - 在主页标题部分,我有一个下拉菜单,其中有两个选项。每个选项都应该路由到不同的 Controller/ActionMethod。因为我需要将它放在每个页面的页眉部分,所以我将它放在 site.master 文件中。

下拉代码:

      <%=Html.DropDownList("OneOrTwo", 
new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "One" },
new SelectListItem{ Text="Two", Value = "Two" }
}
, new { @style = "background-color:#f00; border: none;", onchange =

"fnNum()" }

)%>

在 javascript 文件中,我根据下拉选择路由到不同的 Controller /操作方法。

function fnNum()
{
var e = document.getElementById("OneOrTwo");
var SelValue = e.options[e.selectedIndex].value;

if (SelValue == "One")
window.location.href = "Controller1/Index";

else
window.location.href = "Controller2/Index";
}

这种方法有两个问题:

  1. 更改选择时 - 新选择的选项不会保留。即使网页显示新的 Controller /操作方法 View ,下拉菜单也会切换回原始选择...

  2. 在相同选择的后续选择中 - 带我到 localhost:/Controller1/Index/Controller1/Index/etc..... 必须有一个干净的方法来做到这一点。

所以我想要两件事:

  1. 应保留更改的选择。
  2. 在随后的选择中,每次都需要将控件正确路由到 controller/index,而不是 controller/index/controller/index...等。

感谢您的帮助。

最佳答案

要解决问题 1,您必须设置 SelectListItemsSelected 属性。所以我会更改您的代码以生成如下所示的下拉列表:

@Html.DropDownList("FooOrBar", new List<SelectListItem> {
new SelectListItem{ Text="One", Value = "Two", Selected = Request.Path == "/Controller1/Index" },
new SelectListItem{ Text="One", Value = "Two", Selected = Request.Path == "/Controller1/Index" }
}, new { @style = "background-color:#f00; border: none;", onchange = "fnNum()" } )

第二个问题比较容易解决。这是因为您将窗口位置设置为相对,而不是绝对 URL。只需将其更改为:

if (SelValue == "One")
window.location.href = "/Controller1/Index";
else
window.location.href = "/Controller2/Index";

关于javascript - 下拉菜单无缝地路由到不同的 Controller /操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com