Ajax comments form in ASP.NET MVC2, howto?
Posted
by Artiom Chilaru
on Stack Overflow
See other posts from Stack Overflow
or by Artiom Chilaru
Published on 2010-04-24T09:35:22Z
Indexed on
2010/04/24
23:53 UTC
Read the original article
Hit count: 535
I've been playing around with different aspects of MVC for some time now, and I've reached a situation where I'm not sure what would be the best way to solve a problem. I'm hoping that the SO community will help me out here :P
I've seen a number of examples of Ajax.BeginForm on the internet, and it seems like a very nifty idea. E.g. you have a dropdown where you select a customer - and on selecting one it will load this client's details in some placeholder on the page. This works perfectly fine.
But what to do if you want to tie in some validation in the box?
Just hypothetically, imagine an article page, and user comments in the bottom. Below the comments area there's an ajax-y "Add comment" box. When a user adds a comment, it will appear in the comments area, below the last comment there.
If I set the Ajax.BeginForm to Append the result of the call to the Comments area, it will work fine. But what if the data posted is not valid? Instead of appending a "successful" comment to the comments area I have to show the user validation errors.
At this point I decided that the area INSIDE the Ajax.BeginForm will be inside a partial, and the form's submits will return this partial. Validation works fine. On each submit we reload the contents inside the form element. But how to add the successful comment to the top?
Other things to consider: The comment form also has a "Preview" button. When the user clicks on Preview, I should load the rendered comment into a preview box. This will probably be inside the form area as well.
I was thinking of using Json results instead. When the user submits the form, the server code will generate a Json object with a Success value, and html rendered partials as some properties. Something like
{ "success": true, "form": "<html form data>", "comment": "successful comment html to inject into the page" }
This would be a perfect solution, except there's no way in MVC to render a partial into a string, inside the controller (separation of context, remember?).
So.. what should I do then? Any "correct" way to implement this? Anyone???
© Stack Overflow or respective owner