Ajax.BeginForm on DropDownList change

Recently I’ve encountered a problem on how to perform AJAX POST with helpers provided by ASP.NET MVC 5 – Ajax.BeginForm on DropDownList change event.

Idea behind

Imagine you have ViewModel like this:

And MVC controller action like this:

My first thought was to to something like this (note I didn’t used TextBoxFor and DropdownListFor because I actually used Ajax.BeginForm to edit attributes of each item in collection of objects inside TestVM, not the TestVM attributes themselves):

However, what I kept receiving was a postback to the /Post address instead of making an AJAX call.
I’ve also added

@Scripts.Render(“~/Scripts/jquery.unobtrusive-ajax.js”)

in several places around thinking it might be rendered wrong but nothing changed.
I’ve also kept changing how, when and where is jquery and jquery-validate loaded but no luck.

Solution

In the end I gave a try something like this (kudos to one of fellow StackOverflow’ers for an answer, can’t find it at the moment):

Yes, that’s right – only change is replacing:

onchange = “this.form.submit();”

with:

onchange = “$(this.form).submit();”

With that you can easily forget about button type=”submit” and move on to more natural way of updating records with Ajax.BeginForm on DropDownList change event.

Leave a Reply

Your email address will not be published. Required fields are marked *