Question

i know that ViewBag and ViewData can be used to pass data and objects from controllers to the corresponding view. Can they be used for vice versa, i.e. to pass data from view to the controller or to bind to model property. I have a file select in the view. Now can i pass that file using ViewBag to the controller or bind that file to my model property?

Thanks

Was it helpful?

Solution

The ViewBag or ViewData containers cannot be used to transfer data back to the controller. This is to due with the fact that the page is Stateless. Therefore once the View has been completely rendered (and all subsequent views) the ViewBag containers are disposed of.

To pass information back to the controller your options are using a HttpGet or HttpPost in the query string or form properties. This can be through traditional requests or via aJax requests.

You CAN however bind a value in your ViewBag \ ViewData to a model property. However that model property must be sent back to the controller using one of the methods above.

Hope this helps.

OTHER TIPS

The life cycle of view bag only lasts for the duration of the initial request, so it won't be defined when you make additional requests. See more here: ViewBag/ViewData Lifecycle.

You can however do something like the following: How can ViewBag data be saved after a form post?

Build route params for future requests etc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top