0

Is it possible to select a dropdown option, in Razor, at runtime?

My case:

I have the need to create one dropdown for every result from a db, and that each have a specific selected options.

In ViewModel I have:

public constructor(){
           var Payment = database.PayType
                            .Select(a => a)
                            .ToList();

            this.List_Payment_Method = new SelectList(Payment, "ID", "Description");

            this.pay_Methods = Payment;
}

On the View (Razor) I need to do a foreach pay_methods so that I create has many dropdowns has the number or results in pay_Methods. The objective is to - at the end - have 'n' dropdown lists, each with a specific option selected.

If pay_Methods.count = 5, I would end with 5 dropdownlists, one for each pay_Method, and each with a diferent selected value.

My Razor:

    @foreach (var pm in Model.pay_Methods)
    {

        <div class="cell colspan3">
                @Html.DropDownList("ID", (IEnumerable<SelectListItem>)Model.List_Payment_Method, "-", new
           {
               @class = "input-control select",
               @id = "Count[" + i + "].ID",
               @Name = "Count[" + i + "].ID",
               data_val_required = Resources.Required,
               @Selected = pm.ID <<<------ with this i wanted to select the option with pm.ID value.... 
           })
       </div>
     }

The result was not what I expected:

<select name="paymeth[0].ID" Selected="9c882rt7-f4ll-4cca-hhff-84f0ggab1001" class="input-control select" data-val="true" data-val-required="Campo Obrigatório" id="dailyCount[0].Fin_Payment_MethodID"><option value="">-</option>
<option value="9c882rt7-f4ll-4cca-hhff-84f0ggab1001">Credit Card</option> <<<------ This is what I wanted to selected
...
<option>more options</option>
</select>

Is it possible to do this in razor or do I need to write javascript to populate the dropdowns?

Thank you

Diogo Almeida
  • 124
  • 2
  • 12
  • Everything your doing here is wrong. Start by reading [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) to understand how to bind to collections. The [this answer](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array/37411482#37411482) to understand how to use a dropdownlist in a collection –  Mar 08 '18 at 02:43
  • Its is a duplicate: the answer would be: Option 2 from "MVC5 Razor html.dropdownlistfor set selected when value is in array " – Diogo Almeida Mar 08 '18 at 02:54

0 Answers0