Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TagHelpers onchange event for Dropdownlist in mvc 6

I am having a dropdown and I want to bind a Jquery onchange event to the TagHelpers select tag. Below is my code.

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

How can I bind bind the onchange event inline of the tag.

Something like this.

 <select asp-for="BusinessType"
         asp-items="@Model.BusinessTypeCollection"
         onchange ="something">
 </select>
like image 239
maxspan Avatar asked Aug 08 '16 02:08

maxspan


1 Answers

onchange is the correct attribute to use if you want to specify it inline. You just need to make sure you are (a) invoking it and (b) that function is available in global scope.

For example:

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

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

That being said, a much better way to do this is by binding the event in JavaScript (I'm using jQuery here as you have mentioned it in the question) and only reference the element by it's id attribute.

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

@section scripts {
    <script>
        $("#BusinessType").on("change", function () {
            alert("changed!");
        });
    </script>
}
like image 175
Will Ray Avatar answered Oct 03 '22 22:10

Will Ray