用于mvc 6中Dropdownlist的TagHelpers onchange事件

时间:2016-08-08 02:44:29

标签: c# asp.net-core-mvc

我有一个下拉列表,我想将Jquery onchange事件绑定到TagHelpers select标记。以下是我的代码。

 <select asp-for="BusinessType"
         asp-items="@Model.BusinessTypeCollection">
 </select>

如何绑定绑定标记内联的onchange事件。

像这样。

 <select asp-for="BusinessType"
         asp-items="@Model.BusinessTypeCollection"
         onchange ="something">
 </select>

1 个答案:

答案 0 :(得分:1)

onchange是您想要内联指定的正确属性。您只需要确保您(a)调用它并且(b)该功能在全球范围内可用。

例如:

<select asp-for="BusinessType"
        asp-items="Model.BusinessTypeCollection"
        onchange="test()"></select>

@section scripts {
    <script>
        function test() {
            alert('hi');
        }
    </script>
}

话虽如此,更好的方式这样做是通过在JavaScript中绑定事件(我在这里使用jQuery,就像你在问题中提到的那样)并且只引用了元素由id属性。

<select asp-for="BusinessType"
        asp-items="Model.BusinessTypeCollection"></select>

@section scripts {
    <script>
        $("#BusinessType").on("change", function () {
            alert("changed!");
        });
    </script>
}
相关问题