javascript - 为什么我的 DropDownList 更改事件无法工作?

标签 javascript jquery asp.net asp.net-mvc razor

我正在尝试制作一个简单的 DropDownList(在 C# 中简单而有趣,但在这种情况下有点令人沮丧),以允许我在我的 MVC 应用程序中导航。

我对 JavaScript 完全没有经验,但我花了一天的大部分时间尝试各种事情,并使用 Chrome 的 JavaScript 控制台来尝试排除故障。

这就是我总结的。

Razor 引擎 View :

<h2>Index</h2>

<p>
   @Html.DropDownList("DDLRegion", new SelectList(ViewBag.Tables), new { @id  = "DDLRegion" }) <br />
   @Html.ActionLink("Area1", "Index", "Area1") <br />
   @Html.ActionLink("Area2", "Index", "Area2") <br />
   @Html.ActionLink("Area3", "Index", "Area3") <br />
</p>

@section Scripts{
 <script src="/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
 <script type="text/javascript">
     $("#DDLRegion").change(function () {
         var selectedItem = $(this).val();

         switch (selectedItem) {
            case '0':
               window.location.href = @Url.Action("Index", "Area1");
               break;
            case '1' :
               window.location.href = @Url.Action("Index", "Area2");
               break;
            case '2' :
               window.location.href = @Url.Action("Index", "Area3");
               break;
            default:
               window.location.href = @Url.Action("Index", "Area1");
               alert("Blarg");
               break;
         }
      });
  </script>
}

JavaScript 控制台的最新错误是提示 @Url.Action 方法的 case '0' block 上缺少/(翻译为最终为 '/Area1')。

最佳答案

window.location.href = @Url.Action("Index", "Area1"); 这将呈现为 window.location.href=sitePrefix/Area1/Index;

现在,window.location.href=sitePrefix/Area1/Index; 不是有效的 JavaScript 语句。表达式的 RHS 应该是一个合适的值。由于这是一个 URL,因此您可以将其视为字符串。

window.location.href = '@Url.Action("Index", "Area1")'; 在 RHS 周围添加单引号即可。

关于javascript - 为什么我的 DropDownList 更改事件无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910350/

相关文章:

javascript - JQuery 和 Fancybox 单击图像打开新页面/链接(更新现有代码)

jquery - 如何让这个 jQueryUI 按钮与使用自定义 CSS 样式创建的按钮大小相同?

asp.net - 如何在弹出窗口中打开aspx网页

asp.net - Angular 5 不会发回身份验证 cookie

javascript - 使用 JavaScript 设置背景颜色会破坏 CSS 悬停行为

javascript - 仅在 Javascript 中在 IE 11 中传递动态日期时获取 "Invalid Date"

jquery - 滚动模态,而不是正文

javascript - 从数组中检索的 var 未定义?

ASP.NET TempData 即使在阅读后也不会被清除

javascript - 将 C# 的 FileTimeUTC 数字转换为 Javascript 中的日期