0

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

tereško
  • 58,060
  • 25
  • 98
  • 150
Why
  • 626
  • 11
  • 29

2 Answers2

1

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.

Nico
  • 12,493
  • 5
  • 42
  • 62
  • i know how to send back the model property to the controller but how can i bind it at the first place...I have a file input type and the file selected needs to be binded to the the model property which is a HttpPostedFileBase property – Why Nov 12 '13 at 06:36
  • In that example you cant set the HttpPostedFileBase property as that has to be set by the browser file control (or file api in html5). If you are trying to bind a value to a model item you simple set the value on the HTML element that will be included on your past. It has to bound to an element that will be posted back to the controller. File inputs do not allow you to set the value. – Nico Nov 12 '13 at 06:38
  • the problem i am having is that its a part of ajax form – Why Nov 12 '13 at 06:39
  • In this example. You will not be able to bind the value for a file. Doing so means you would have access to the file system on the client. – Nico Nov 12 '13 at 06:40
1

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

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135