Autopostback select lists in ASP.NET MVC using jQuery
This tiny snippet of code show you how to have your select
lists autopostback its containing form when the selected
value changes.
When the
DOM is fully loaded, we get all select nodes that have an attribute of
“data-autopostback” with a value of “true”.
We wire up the “change” JavaScript event to all these select nodes. This event is
fired as soon as the user changes their selection with the
mouse.
When the event is fired, we find the
closest form
tag for the select node that raised the event and submit the
form.
$(document).ready(function () {
$("select:[data-autopostback=true]").change(function () {
$(this).closest("form").submit();
});
});
A select tag with autopostback enabled will look like this
<select id="selCategory" name="Category" data-autopostback="true">
<option value='1'>Electronics</option>
<option value='2'>Books</option>
</select>
The reason I am using “data-" suffix in the attribute
is to be
HTML5 Compliant.
A custom data attribute is an attribute in no namespace
whose name starts with the string "data-", has at least
one character after the hyphen, is XML-compatible, and
contains no characters in the range U+0041 to U+005A
(LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).