I have this html...
<select id="View" name="View">
<option value="1">With issue covers</option>
<option value="0">No issue covers</option>
</select>
It won't let me insert code like this...
<select id="View" name="View">
<option value="1" <% ..logic code..%> >With issue covers</option>
<option value="0" <% ..logic code..%> >No issue covers</option>
</select>
So whats the best way to set one to selected?
Update: Without using the HTML Helpers.
The "best" approach is probably to use the helpers:
var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp);
... Html.DropDownList("foo", selectList)
Where "data" could be an array of anonymous types, such as:
var data = new[] {
new {Key=1, Text="With issue covers"},
new {Key=0, Text="No issue covers"}
};
// todo: pick the selected index or value based on your logic
var selectList = new SelectList(data, "Key", "Text", data[1].Key);
Writer.Write(Html.DropDownList("foo", selectList));
Another approach might be to select the correct item client-side through script, but obviously that only works with script enabled.
Note it was missing comma and semicolon in data declaration, stopped it from working
I would agree with Marc on using helpers but if you must avoid them then you could try something like the following:
<select id="View" name="View">
<option value="1" <% if (something) { %> selected <% } %> >With issue covers</option>
<option value="0" <% if (!something) { %> selected <% } %> >No issue covers</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With