views:

33

answers:

2

Hello,

i want to keep a List in the controller. and manipulate it via action the being invoked from a view page. currently i'm losing the data of the List on each request. what is the correct way to do that in ASP.NET MVC

Thanks

A: 

Since the controller is re-instantiated on each request, you can't.

Instead, use a database of some kind - there are really fast ones out there, if performance is the reason you wanted a list in the first place. Try SQLite, for example. I haven't done any real work with it myself, but from what I've heard it's really high-performing both for in-memory databases and file based.

An option could be some sort of singleton pattern, that instantiates the list on application start and then keeps it static for as long as the application runs. Not sure exactly how you'd do that though.

Tomas Lycken
Woah woah woah. There are a number of ways to preserve state in MVC from throwing things in the Session[] to Serializing it on the page and manipulating it from javascript or just using model binders round trip an object.
jfar
@jfar, to me it was apparent that the OP didn't want one of those solutions - he wanted a private field of type `List<T>`, which he could use with preserved state. And that *is* impossible.
Tomas Lycken
Wow, all that from a very vague question? What made you think the field was private? To me it sounds like he is new at MVC and doesn't understand his options yet.
jfar
@jfar, Private or not, that seems the most logical to expect when dealing with a data store for a class in this way. I too realized that he was new to MVC, and suggested different (better) approaches, for example using a db - real or pseudo.
Tomas Lycken
Yes I am new to ASP.NET MVC coming from J2EE, mostly Struts, so i'm not new to the MVC concept or programming.I need an object that i can keep it's state for as long as the application runs. i do not want to put hidden strings on the client or using the DB.Is it wrong to use the session? what my options?i hope i am making more sense now. thanks.
fox
Session is a decent alternative for what you're trying to do (although I still want to question your goal... One of the points with MVC is that it, like the web itself, is stateless). Later in the development process you probably want to abstract the actual session handling away from the controller, and into an actionfilter. See point seven here: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
Tomas Lycken
A: 

You can post that data in hidden fields and have it modelbind back (like in this example) or manage it in Session.

RailRhoad