I have a list of type List<JobSeeker>
. I want to store it in ViewState. How this can be done?
private List<JobSeeker> JobSeekersList { get; set; }
Yes. We can store object in ViewState as it stores the data in the string form although it works like dictionary. Just serialize the object and store the string in ViewState.
Viewstate data is sent to and from the server to client on each and every postback thus causing the user to download that information every time. The more data stored in viewstate, the slower the page will load. But to answer your question, there is not a size limit to viewstate.
View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls. You can also use view state to store application data that is specific to a page.
Basically you only need to use the get
, then on get you either get the posted data from view state, or set it for the first time on the view state. This is the more robust code to avoid all the checks on each call (is view state set, exist etc), and direct saved and use the view state object.
// using this const you avoid bugs in mispelling the correct key.
const string cJobSeekerNameConst = "JobSeeker_cnst";
public List<JobSeeker> JobSeekersList
{
get
{
// check if not exist to make new (normally before the post back)
// and at the same time check that you did not use the same viewstate for other object
if (!(ViewState[cJobSeekerNameConst] is List<JobSeeker>))
{
// need to fix the memory and added to viewstate
ViewState[cJobSeekerNameConst] = new List<JobSeeker>();
}
return (List<JobSeeker>)ViewState[cJobSeekerNameConst];
}
}
Alternative to avoid the is
// using this const you avoid bugs in mispelling the correct key.
const string cJobSeekerNameConst = "JobSeeker_cnst";
public List<JobSeeker> JobSeekersList
{
get
{
// If not on the viewstate then add it
if (ViewState[cJobSeekerNameConst] == null)
ViewState[cJobSeekerNameConst] = new List<JobSeeker>();
// this code is not exist on release, but I check to be sure that I did not
// overwrite this viewstate with a different object.
Debug.Assert(ViewState[cJobSeekerNameConst] is List<JobSeeker>);
return (List<JobSeeker>)ViewState[cJobSeekerNameConst];
}
}
and the JobSeeker
class must be [Serializable]
as
[Serializable]
public class JobSeeker
{
public int ID;
...
}
and you simple call it normally as an object and will never be null. Also will be return the saved on viewstate values after the post back
JobSeekersList.add(new JobSeeker(){ID=1});
var myID = JobSeekersList[0].ID;
private IList<JobSeeker> JobSeekersList
{
get
{
// to do not break SRP it's better to move check logic out of the getter
return ViewState["key"] as List<JobSeeker>;
}
set
{
ViewState["key"] = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With