Category - Projects

ListView Data in Session State

jfsession

With each new project I tend to gravitate towards a new aspect of coding that I haven't done before. At least one new challenge that will push me a bit farther.

For this project, I wanted to keep a list of contacts phone numbers in a one to many table. When it came to editing a contact, it would be very simple to nest a ListView inside the FormView's modal popup. Slap it in an update panel and it'll live in it's own little world tied to an SQL DataSource and doing all the work.

However, when it came to adding a new contact... ahhh, now there's where the problem comes in. See, we can't add that data to the database yet as we don't know what the new contact's ID number is going to be. So where do we store it? How do retrieve it? Better yet, what if the user needs to make some changes to that information before submitting the contact's info?!

The solution:

Since I had already setup a Linq to Sql class, I already had a "phone" datatype. So, on the prerender event of the ListView nested in the insert template, I created a List and then checked to see if that was in the session. If so, I pulled it out and populated the ListView with it. If not, I just connected the ListView to the empty collection. Then added that list to the session.

From there on the inserting, deleting and updating events of the ListView, I created the list, checked for it in session, got it if it was there. Made changes and sent it back to the session.

Rinse and repeat!

Finally, after initially creating the actual contact, I pulled that data one more time from the session, inserted the records with Linq and cleared the session. :)

Sounds so easy to explain now... it took a bit of fiddling to figure out. Gotta love the debug mode of visual studio to really let you explore an object or collection though :)

You must be logged in to comment.