How do you submit from a dropdownlist "onchange" event from inside of an ajax form?
According to the following question: How do you submit a dropdownlist in asp.net mvc, from inside of an Html.BeginFrom you can set onchange="this.form.submit" and changing the dropdown posts back.
However, using the following code (inside an Ajax.BeginFrom):
<% using (Ajax.BeginForm("UpdateForm", new AjaxOptions() { UpdateTargetId = "updateText" })) { %>
<h2>Top Authors</h2>
Sort by: <%=Html.DropDownList("sortByList", new SelectList(ViewData["SortOptions"], new { onchange = "this.form.submit()" })%>
<%= Html.TextBox("updateText")%>
<% } %>
Posts back to the controller action, but the entire page is replaced with the contents of the "updateText" text, rather than just what is inside the "updateText" textbox.
Thus, rather than replacing just the area inside the Ajax.BeginForm, the entire page is replaced.
What is the correct way for the dropdownlist to call this.form.submit such that only the area inside the Ajax.BeginForm?
I had the same problem too. I had several dropdown lists in partial views so they could refresh independently, but setting the "onchange" attribute kept refreshing the entire page.
I noticed that "this.form.submit()" always referred to the main form, outside the partial view. So instead I added a submit button inside the AJAX form and referred to that:
My "Model.IdIdex" is just a variable to access different controls in the same page. Hope it helps.
I had a button like this in my AJAX.BeginForm
And onsubmit or the solution from Francisco didn't work (I still don't know why)
So I created an alternative:
OK, nearly 2 years later, you probably don't care anymore. Who knows: Maybe others (such as me ;-) do.
So here's the (extremely simple) solution:
In your
Html.DropDownList(...)
call, changeto
Can you spot the difference? ;-)
The reason is that
Ajax.BeginForm()
creates a form with anonsubmit()
handler to submit the form asynchronously. By callingsubmit()
, you bypass thisonsubmit()
custom handler. Callingonsubmit()
worked for me.in your dropdown replace
to
If you are using MVC then probably the best way is with jQuery...
Your controller would be something like:
What you can try to do it this (jQuery required):