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