views:

1722

answers:

4

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.

+4  A: 

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.

Marc Gravell
+1  A: 

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>
Todd Smith
I tried something like this but it didn't work. I tried your code and it worked! I must of did something wrong. Since the IDE highlights it funny I thought that you couldn't put markup there. Obviously I was wrong.Thanks!!
Donny V.
A: 

I think the helpers are the best way to go.

If you don't pass a "selected value" (4th param in SelectList constructor) than it will be loaded from the ModelState if one is available. This is very handy when you are dealing with post backs and want to have MVC automatically maintain the state of your form across loads. You can set a condition to only use the override with the "selected value" option if it is a first load, then leave it to MVC and the HtmlHelpers to manage the state after that.

View Markup:

<%= Html.DropDownList("RdfParser", ViewData["RdfParserTypes"] as SelectList) %>

Controller:

var rdfTypes = new[]
    {
        new { value = 0, text = "RDF/XML" },
        new { value = 1, text = "NTriples" },
        new { value = 2, text = "Turtle" },
        new { value = 3, text = "RDFa" }
    };
ViewData["RdfParserTypes"] = new SelectList(rdfTypes, "value", "text", rdfTypes[0]);
spoon16