Is there a tutorial or code example of using Ajax.BeginForm
within Asp.net MVC 3 where unobtrusive validation and Ajax exist?
This is an elusive topic for MVC 3, and I cannot seem to get my form to work properly. It will do an Ajax submit but ignores the validation errors.
Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,
Only these two are enough for performing Ajax operation.
Example:
Model:
Controller:
View:
and here's a better (in my perspective) example:
View:
index.js
:which can be further enhanced with the jQuery form plugin.
I got Darin's solution working eventually but made a few mistakes first which resulted in a problem similar to David (in the comments below Darin's solution) where the result was posting to a new page.
Because I had to do something with the form after the method returned, I stored it for later use:
However, this variable did not have the "action" or "method" properties which are used in the ajax call.
Instead you need to use the "this" variable:
I think that all the answers missed a crucial point:
If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:
Otherwise you will end like @David where the result is displayed in a new page.
Darin Dimitrov's solution worked for me with one exception. When I submitted the partial view with (intentional) validation errors, I ended up with duplicate forms being returned in the dialog:
To fix this I had to wrap the Html.BeginForm in a div:
When the form was submitted, I cleared the div in the success function and output the validated form:
If no data validation excuted, or the content is always returned in a new window, make sure these 3 lines are at the top of the view: