【问题标题】:ASP.NET MVC 3 with Razor DropDownListFor change not firing带有 Razor DropDownListFor 的 ASP.NET MVC 3 更改未触发
【发布时间】:2011-12-11 20:07:28
【问题描述】:

我在这里看到了很多关于 DropDownList 和 DropDownListFor 事件没有触发但没有解决我问题的答案的问题。我认为我没有忽略任何事情,所以我会发布我自己的问题...

我的视图中有以下代码:

@model MyWebApp.ViewModels.ProductAdminViewModel
@{
    ViewBag.Title = "Manage Products";
}
<script type="text/javascript">
    $(function () {
        $('select#CurrentCategoryId').change(function () {
            alert('We got here!');
        })
    });
</script>

@using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "indexGrid" }))
{ 
    <fieldset>
        <legend>Select Category</legend><span>Category: </span>
        @Html.DropDownListFor(model => model.CurrentCategoryId, Model.CategorySelectList, new { @id = "CurrentCategoryId" })
    </fieldset>
}
<div id="indexGrid">
    @Html.Partial("_indexGrid", Model)
</div>

下拉列表是从我的 ViewModel 中的 SelectList 正确填充的,唯一需要注意的是 VM 中的 CurrentCategoryId 是公共 int 属性。

在将下拉菜单绑定到脚本时我忽略了什么?

编辑:我的 _Layout.cshtml 文件中有以下内容:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="/Scripts/prototype.js"></script>
<script type="text/javascript" src="/Scripts/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="/Scripts/lightbox.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript" src="/Scripts/EditorTypes.js"></script>

感谢@Hawkke。这是我的工作代码:

<script type="text/javascript">
    function CategoryChanged(newCategoryId) {
        alert('The category has been changed!');
    };
</script>
...
@Html.DropDownListFor(model => model.CurrentCategoryId, Model.CategorySelectList, new { @onchange = "CategoryChanged(" + @Model.CurrentCategoryId + ")" })

【问题讨论】:

  • 你有没有在任何地方引用过 jQuery?
  • 你能粘贴html输出吗?

标签: asp.net-mvc razor html.dropdownlistfor


【解决方案1】:

'select#CurrentCategoryId' 需要一个名为“CurrentCategoryId”的控件,但下拉列表的名称是 VM 的 ID。

编辑

我要做的是将您的 javascript 从 jQuery 函数更改为常规函数。

<script>
    function ChangeMe(currentCategoryId) {
        // do stuff here
    }
</scrip>

然后更改您的 html 助手:

@Html.DropDownListFor(model => model.CurrentCategoryId, Model.CategorySelectList, 
    new { onchange = "ChangeMe(@Model.CurrentCategoryId)" })

我不是 100% 了解 razor 语法,但我想你明白了。

【讨论】:

  • 是否 ", new { @id = "CurrentCategoryId" }" 不提供该链接?
  • 编辑:我认为你是对的,我没有看到你没有指定@id = Model.CurrentCategoryId,而是实际的字符串“CurrentCategoryId”。请参阅我的编辑以了解我会如何做。
  • 感谢 hawkke,这让我走上了正确的道路。我已经在问题下方发布了完成的代码,供感兴趣的人使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2011-11-09
相关资源
最近更新 更多