Alternative to reloading model data

I have a controller view that lists recent comments. I also have a textbox and a button to add a new comment. When I submit a message to the Save action, I need to check the text box. However, if the check fails, when returning to the view, I also need to reload all comments again, which seems like an unnecessary db call.

Example: My action contains a parameter called a comment. If the comment is invalid (empty or contains profanity) Create a new ViewModel. Load the previous comments from db. Add comments to ViewModel AddModelError for comment. Return type (model).

Is there no way to keep the originally loaded comments so that it doesn't hit the db again?

+2


source to share


3 answers


There are many ways to store comments, but in this case, calling db might not be all that bad. But the answer to what I think is the root of your question is that there is no built-in way to just magically preserve the original comments.

These are not web forms, so you won't have all the comments in the ViewState (which is good!) How Web Forms magically saved a lot of data through post-backs. The POST to your Save action and rendering the resulting view is not fundamentally different from the GET on your last comment page - and if the request from the database is ok on the comments page, then it should be ok with the Save in my opinion.



Having said that, there is room for improvement, and AJAX is probably one of your best options. Using jQuery or MS Ajax ( Ajax.BeginForm()

), you can call a save method that does its job, and only return the comment you just saved by adding it to the comments on your page. Not only did you save the db call, but you also improved the user experience!

+2


source


Of course, the biggest candidate here is cache usage and possible dependency on it, so the cache for that particular set of information only invalidates if the database table for them is changed. You can also add time for added efficiency.



Andrtew

0


source


Perhaps you could use "TempData" to pass the result to the next controller request. This usually works well when you know what the next request will be?

0


source







All Articles