1. Original Entry + Comments2. Write a Comment3. Preview Comment

May 19, 2012  |  "Remembering" a selection in a <select> list in Razor  |  55951 hit(s)

I'm just recording this for now, possibly for later investigation. In ASP.NET Web Pages 2 (Razor), you can take advantage of conditional attributes to set or clear attributes like selected and checked. These attributes don't need a value, they just need to exist, like this:

<option value="1">One</option>
<option value="2" selected >Two</option>
<option value="3">Three</option>
So how do you "remember" a list selection after a form submit? Here's one way. This seems a bit kludgy, but I can't offhand think of a way to do this without using JavaScript or something.

< select name="NumberList">
selected=@(Request.Form["NumberList"] == "1")
selected=@(Request.Form["NumberList"] == "2")
selected=@(Request.Form["NumberList"] == "3")