tags:

views:

56

answers:

3

I have a controller view which lists recent comments. I also have a textbox and button to add a new comment. When I post to the Save action, I need to validate the textbox. However if the validation fails, when returning to the view, I also need to reload all the comments all over again, which feels like an unnecessary db call.

Example: My Action contains a parameter called comment. If comment if invalid (blank or contains profanity) Create a new ViewModel. Load the previous comments from db. Add comments to ViewModel AddModelError for the comment. Return View(model).

Is there no way of retaining the comments originally loaded, to prevent hitting the db again?

A: 

Ofcourse the biggest candidate here is to use Cache, and possible use a dependency on there so that the cache for that particular set of information only invalidates if the database table for them is modified. You could add a time expiration too for extra efficiency.

Andrtew

REA_ANDREW
+2  A: 

There are many ways that you could retain the comments, but in this scenario a db call may not be that bad of an option. But to answer what I think is the root of your question is that there is no "built-in" way to just magically keep the original comments.

This is isn't Web Forms, so you're not going to have all the comments in ViewState (good!) which was how Web Forms magically retained a lot of data across post-backs. A POST to your Save action and the rendering of the resulting view isn't fundamentally different than a GET to your recent comments page - and if querying from a database is okay on the comments page, then it should be okay on the Save in my opinion.

Having said that, there is room for improvement and AJAX is probably one of your best options. Using either jQuery or MS Ajax (Ajax.BeginForm()) you could call the save method which does its thing and only return the newly saved comment, appending it to the comments on your page. Not only did you save a db call, but you improved the user experience!

Kurt Schindler
+1 ViewState was a great idea if you wanted to slow down a page. :) jQuery would be an awesome choice here but if many ppl are posting comments you may want to reload them as in the time it took me to type this, someone else may have added a comment.
griegs
A: 

Perhaps you could use "TempData" to pass the result to the next controller request.. this generally works well when you know what the next request is going to be?

Mark