May 19, 2012
|
"Remembering" a selection in a <select> list in Razor
|
61247 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:
<select>
<option value="1">One</option>
<option value="2" selected >Two</option>
<option value="3">Three</option>
</select>
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">
<option
selected=@(Request.Form["NumberList"] == "1")
value="1">One</option>
<option
selected=@(Request.Form["NumberList"] == "2")
value="2">Two</option>
<option
selected=@(Request.Form["NumberList"] == "3")
value="3">Three</option>
</select>