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
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.