ASP.Net MVC - Sending an object from controller to view to controller
I'm just starting with ASP.Net MVC 2 and might be doing something wrong. I have a controller who builds some objects and passes them to a view using ViewData. In the view I display the data etc ... and then want to submit the same data (plus other user input) back to the same controller. Is there any simple way to do this ?
I'll provide a more detailed description of the problem if necessary.
Thanks and good day :)
EDIT : I read more on ViewModels fearing that I wasn't using them properly but apparently they're not a solution. My problem isn't getting data to the view (I already use a view model for that), but returning the data back to the controll开发者_JAVA百科er. I use complex objects, so even sending a form with hidden fields wouldn't really be a good solution as it will require me to serialize my objects, which is too much hassle for a task that should be simple. I'm going to have a look at sessions for now.
EDIT 2: Ok, I solved the problem using sessions, couldn't be easier :)
Consider any of these solutions to keep state between requests:
- keep that data in Session, Cache, or cookies. The choice will depend on what that data is, how variable the data is between users, and how complex it is.
- write those items to hidden inputs.
Html.Hidden("foo", myData);
If you choose to write to hidden inputs, consider faking ViewState. It's a non-optimal solution though.
I'd prefer Session overall. There's no tampering, and you can hold complex objects. Obviously the drawbacks to Session are future scaling performance, timeouts, and concurrency with multiple sessions. Some of those problems can easily be mitigated, though.
I have a controller who builds some objects and passes them to a view using ViewData
Wrong: define a view model class and make your view strongly typed to this model instead of using ViewData
.
Once the view is rendered you will have a form and you should put everything you need to get back in this form: visible input fields that the user will manipulate and hidden fields that will contain any context you would like to get in the action you are posting to.
Another option is to store this information into cookies or session.
Look at some examples of the View Model. that should be favored against using the ViewData stuff.
e.g. http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx
with that, you are on the whole chain typesave, and you can recieve the whole model as a parameter on the post back.
精彩评论