开发者

Pattern for AJAX Form Submissions in ASP.NET MVC

Here is what I would like to be able to do:

  1. Display a dialog box containing a form to create a new record (for example a user)
  2. Form is submitted via AJAX.
  3. Get response that can be either the same form with validation errors or the new record in JSON format.

Some additional information:

  • I am using partials to render the form. 开发者_运维知识库So when the dialog is first displayed I make an ajax call to get the empty form markup and when the form is submitted I will use the same partial if the form has validation errors.
  • If the response comes back and there are validation errors then I just want to replace the existing form markup with the returned markup.
  • If the response comes back and there are not validation errors then I would close the dialog and take the JSON formatted object and make some other changes to the page.

I some parts of this working fine. The problem is that if I were to pass back a JSON formatted object on success instead of HTML I can by definition never be sure what the return type will be. My first though was to always return JSON from AJAX calls. If the form had validation errors the returned JSON would have a property called "html" that would contain the updated form markup. If there are not validation errors then the returned JSON would have a property called "data" which contains the newly created object.

I think my solution will work, but I wonder if anyone else has come up with something more elegant. I would imagine this basic flow must be common in other applications, so I can't be the only one looking for a solution to this problem.


You mentioned you'd like to add client-side validation... then you will need a way to display validation errors in the client-code. If you have that, then instead of returning HTML from your AJAX call, you can instead return a list of validation errors in JSON, and plug those into the same error-display methods you have for the client validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜