【问题标题】:Why can't I get my DropDownList change event work?为什么我的 DropDownList 更改事件无法正常工作?
【发布时间】:2015-04-28 04:28:56
【问题描述】:

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

我完全没有使用 JavaScript 的经验,但我大部分时间都在尝试各种事情,并使用 Chrome 的 JavaScript 控制台尝试解决我能做的事情。

这是我总结出来的。

Razor 引擎视图:

<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' 块上缺少 /(转换为最终为 '/Area1')。

【问题讨论】:

  • 尝试将 @Url.Action.. 用引号括起来 '' - window.location.href = '@Url.Action("Index", "Area1")'
  • 是的,这行得通,谢谢。

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


【解决方案1】:

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 周围附加单引号会起作用。

【讨论】:

  • 不敢相信我如此接近并偶然发现了如此简单的事情,感谢您的回答。
猜你喜欢
  • 2022-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
相关资源
最近更新 更多