MVC - Check drowdownlist value in real time

131 views Asked by At

How can I check the dropdownlist selectedvalue in real time in MVC, everytime the selected value is changed?

<div class="modal-body">
     Ticket Category:     @Html.DropDownList("TicketCategory", (SelectList)ViewBag.TicketCategory, "--Select Category--")
    </div>
    @if(TicketCategory.SelectedValue == "")
    {
        //do
    }
    else
    {
        //do 
    }

In this case the TicketCategory is not found, am I missing some conversion or do I have to retrieve the element?

1

There are 1 answers

0
Razvan Dumitru On

For DropDownList you have an extra parameter for declaring some htmlAttributes.

From my point of view you always must flag your inputs that you're listening to with some js-smth class.

RAZOR:

<div class="modal-body js-modalBody">
     Ticket Category:     @Html.DropDownList("TicketCategory", (SelectList)ViewBag.TicketCategory, "--Select Category--",  new { @class = "js-ticketCategory" })
</div>

After this you can add a script tag, listening to change event of the input. Assuming that you search for a value that is "3", here is your code.

<script>

$('.js-modalBody').on('change', '.js-ticketCategory', function (ev) {
    if ($(ev.currentTarget).val() == "3") {
        // do something 
    } else {
        // do something else 
    }
});

</script>

P.S: Having javascript in your views isn't a beatiful approach.