0

I have a controller with a get and post action, on the post it checks if the model state is valid. If it is valid the page process the data and redirect. If the model state is not valid it will return the view back with the model. To ensure the drop downs have data I need to repopulate the items from the database which means I need to make another call to the database.

Is there any way to cut the call out to the database by caching or any other method?

rae1
  • 6,066
  • 4
  • 27
  • 48
Funky
  • 12,890
  • 35
  • 106
  • 161
  • what if another user has modified it? – T McKeown Jun 17 '14 at 14:38
  • Have look at the [TempData, ViewBag, ViewData](http://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata) – sestus Jun 17 '14 at 14:46
  • Yes, you can store the result of the first call to db in cache... and in the second call, you check if the cache has data and if it does, use it. If not... you load it again. Keep in mind the time you need the data to be valid, and if its app wide or just for a user. – Romias Jun 17 '14 at 14:47

2 Answers2

2

The problem is that the browser is only submitting the values for your drop downs and not the text. You could get around this by creating a hidden element which submits the text in addition to the values.

But is that a good idea? In my opinion, no. You're creating extra network traffic between browser and the server in order to save traffic between the server and the database. In most cases it will be more efficient to retrieve the data from the database than the client.

Also, the data may have changed between when you sent it to the client and when you send it back the second time.

RyanB
  • 757
  • 4
  • 11
0

Ryan has a good point. I'm assuming you're coming from a WebForms background where everything was cached in the view state and posted back to the server. Asp.net MVC by its very architectural lends itself to a different approach where it's standard to re-query the database for data presentation to the user i.e. dropdown list values.

So you should only post back to the server the values the user has input. This is happening via the view-model. I would make a common method which accepts your view model and does the standard database pull and map to model. This way you can use the same method for the initial Get request and also for validation failure post-backs.

Also, if we're talking about small data sets then I would most definitely re-query as it's not expensive to do. If the drop down lists are huge then it depends on the data itself. Does this data change infrequently? Then it might be feasible to cache it on the web-server in a static list. If it does change frequently then you could look into more advanced solutions like memcached or redis.

pantuofermo
  • 160
  • 7