views:

44

answers:

2

In my view I have an HTML DropDownList that is filled, in my controller, using a List<string>.

<%= Html.DropDownList("ReportedIssue", (IEnumerable<SelectListItem>)ViewData["ReportedIssue"]) %>

List<string> reportedIssue = new List<string>();
reportedIssue.Add("All");
reportedIssue.Add(...);
ViewData["ReportedIssue"] = new SelectList(reportedIssue);

In my view the result is:

<select name="ReportedIssue" id="ReportedIssue">
    <option>All</option>
    <option>...</option>
</select>

Is there a way to do this and also include a value in each of the <option> tags like so?

<select name="ReportedIssue" id="ReportedIssue">
    <option value="0">All</option>
    <option value="1">...</option>
</select>

Thank you,

Aaron

+1  A: 

Can you just loop over the list and output it in the view?

(Also to pass the Id as well as the Text I would create a Dictionary and add it to your view model/ViewData).

In the view:

    <select name="ReportedIssue" id="ReportedIssue">
        <option value="0">All</option>
<% foreach(int key in myDictionary.Keys) { %>
        <option value="<%= key %>"><%= myDictionary[key] %></option>
<% } %>
    </select>
Michael Shimmins
+2  A: 

You can do it with just a slight modification to your code. You will need to decide how you want to define your value item. For now I just put in a comment where you can do it:

ViewData["ReportedIssue"] = new SelectList(reportedIssue
    .Select(r => new SelectListItem 
        { 
            Text = r, 
            Value = someIdValue  // define this however you want
        }));

So just replace your code with this one and implement the someIdValue placeholder.

Kelsey