Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value of a select element's selected property

I am using webmatrix, razor syntax and cshtml file.

I have an "edit" page for a database record which contains a select box(id="selStatus"). I am trying to set the "selected" value of the select box dynamically, based on the value of the current record being edited.

I have the current value or its index in local var's but i cant seem to assign this value back to the select.

if (currentStatus=="Completed"){
    selStatus.options[1].selected=true;
}

RES = error: The name 'selStatus' does not exist in the current context.

I am missing something obvious here but can't seem to get it. Any ideas appreciated. Thanks

like image 379
rusty coder Avatar asked Apr 16 '11 17:04

rusty coder


1 Answers

If you have a static list of options, for example, for Marital Status, you can keep it more legible (for some of us) like this:

<select>
  <option value="Single"   @(marStat == "Single"   ? "selected" : "")>Single</option>
  <option value="Married"  @(marStat == "Married"  ? "selected" : "")>Married</option>
  <option value="Divorced" @(marStat == "Divorced" ? "selected" : "")>Divorced</option>
  <option value="Widowed"  @(marStat == "Widowed"  ? "selected" : "")>Widowed</option>
</select>

What this does is that if your razor variable marStat containing the value that you retrieved from the database matches the string in the condition, it renders "selected" into the HTML. It's a bit of "brute" style but I believe it's very readable.

like image 161
Amarundo Avatar answered Oct 18 '22 19:10

Amarundo