Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to set a dropdown to selected in ASP.NET MVC markup?

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.

like image 455
Donny V. Avatar asked Jan 24 '23 23:01

Donny V.


2 Answers

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

like image 172
Marc Gravell Avatar answered Jan 31 '23 18:01

Marc Gravell


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>
like image 29
Todd Smith Avatar answered Jan 31 '23 20:01

Todd Smith