1

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 文件中,我有这个根据下拉选择路由到不同的控制器/操作方法。

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. 更改选择时 - 新选择的选项不保留。即使网页显示新的控制器/操作方法视图,下拉菜单也会切换回原始选择...

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

所以我想要两件事:

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

谢谢您的帮助。

4

1 回答 1

2

Selected要解决问题 1,您必须设置SelectListItems. 因此,我会更改您的代码以将下拉列表生成如下:

@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 ,而不是绝对URL。只需将其更改为:

if (SelValue == "One")
    window.location.href = "/Controller1/Index";  
else
   window.location.href = "/Controller2/Index";  
于 2012-05-10T19:48:12.140 回答