5

I have 2 dropdown lists in MVC 3 razor view like this:

@Html.DropDownListFor(m => m.UserGroups, Model.UserGroups.Select(x => new SelectListItem() { Text = x.Name, Value = x.Id }), new { @class="pad5" })

They work fine. I have 3 changes to make -

1) First one needs a new option to be added at the top of this list.

<option value="">--pick--</option>

2) And the second one needs to select a specific option upon load. Say I want to pre-select this option on my second list.

<option value="100">My Friends</option>

3) both dropdowns have same data source. This causing both list to have same name on the form. How do I change the name?

I am able to change the id, but the name seems not changing if I add this to the end:

new { @id="ViewGroup", @name="ViewGroup"}
kheya
  • 7,546
  • 20
  • 77
  • 109
  • I can do this by jquery after page load. But prefer to do it in the razor view declarations. – kheya Jun 06 '11 at 18:11

1 Answers1

3

If you have a viewmodel created, you can simply do for each dropdown:

@model Namespace.myViewModel
<select id="dropdownOne" name="dropdownOne">
    <option   value="">--pick--</option>
    @foreach (var item in Model.myModel)
    {
        if(@item.id==100) {
            <option value="@item.id" selected="selected">@item.Name</option>
        }
        else {
            <option value="@item.id>@item.Name</option>
        }
    }
</select>
Bob.
  • 3,894
  • 4
  • 44
  • 76
  • 1
    Instead of manual looping/building the dropwown, can this be done using Html.DropDownListFor() declaration I have? – kheya Jun 06 '11 at 18:33
  • I don't know to be honest, I tried it with DropDownListFor, but the problem is that for my programming, I have a lot of conditionals, so it was a pretty long line, and I found this way personally easier. – Bob. Jun 06 '11 at 18:39
  • 1
    @kheya Yes, you can. But doing it with just Razor allows some flexibility not possible with `@Html.DropDownListFor` alone is some specific scenarios. For example, I need to add `data-` attributes to my HTML passing a `SelectListItem` as a List, to the model. Something not possible with that helper (as far as I know): https://stackoverflow.com/questions/17665426/selectlistitem-with-data-attributes – carloswm85 Jun 21 '22 at 15:21