ASP.NET MVC2 Save data between actions?
Hi,
I have a View that contains some input fields, some of these fields is regular file inputs. When submitting this view form the files will be saved in temp folder. But if there is a validation problem that is detected on the service side then the same view will be returned(for update). The problem is that the file inputs will not be populated again(security) and instead I have to extend the viewclass and show a small thumbnail of the stored files and also make it possible to remove(to be able to upload another file instead).
When the user hit submit again the viewclass will not contain any data about the stored files. How is best practice for this?
My own thought is one of the following :
- Use hidden fields, but thi开发者_JAVA技巧s will be complex when the class to store is complex and it will also not be that secured.
- Use Session to store the data, I do not see if this is a good or bad solution?
- Create a singelton class(like a cache) where all this data will be saved temporerly. ASP.NET had a cache where you could set a time until releas of the chache, this would work in the same way.
- Save the ad as temporary in the database, this would mean that when the view returns it is really an edit of a created ad instead of a edit of a temporary ad(not in database). The problem might be if the user aborts after the first service validation, then we will have an ad that is not complete in database. Another minus is that the id count(identity) will be increased even if the ad is never used. And the last problem with this solution is that the ad table will contains ads that is incomplete.
Pleas advice
My Solution : I ended up to use the System.Web.Cache for keeping data between requests. When a ad is created and accepted it will be removed from the cache and added in database.
You can use MVC's TempData
feature. Essentially TempData
is a session based store that caches data until the next request. You could store a list of existing files for each request and persist it to TempData
(and subsequently read it) each time you process the form?
I solved this problem using the jquery form plugin: http://jquery.malsup.com/form/
This way the file is send via ajax (with the use of iframes internally by the plugin) where a JsonResult is returned (ie you can perform server side validation etc) and the form on the page is effectively unchanged, where you can resubmit without having to select the files again.
Note: If you return a JsonResult in MVC using the plugin, you will need to wrap the JsonResult in a "textarea" tag. see this post for a class that wraps JsonResult and sorts out the testarea anomaly: http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/
精彩评论