I have a page with a form displayed in a modal window to create a model.
I would like to post my form asynchronously via an AJAX link, and handle the server response differently based on whether the model was successfully saved or not.
If the model is saved successfully, my controller redirects to an action called ajaxView which uses renderPartial to return an HTML view of the newly saved model. I want the client to close the modal form window and insert the ajaxView into my document.
If the model is not saved (due to validation error, etc…), the controller returns via renderPartial the model’s form view and I want the client to insert the form view into the modal window.
My challenge is that in both case, my AJAX calls are treated as successful, and they both return fully formed HTML content. I don’t know how to implement a logic to handle the server’s response differently based on whether the HTML returned is an error form view or a model view.
Do you have any tip that would allow me to achieve this?
Instead of returning a string containing the HTML of your rendered view, you can return a JSON object containing an indicator to what you want the client to do.
yes, it’s a good idea. I could have my controller return a JSON object and then have the client send a request to either get the ajax view or the form with error, but it’s a bit cumbersome to add this extra logic on the client side.
I suppose I’ll do this if there isn’t any other option.