DropDownListFor How to set default value in ASP.NET MVC

Html.DropDownListFor How to set default value in ASP.NET MVC


In ASP.NET MVC view, I am using drop down-list box:


<div class="col-12 col-md-6">
    <div class="form-group">

        @Html.LabelFor(m => m.currency)
        @Html.DropDownListFor(m => m.currency, new SelectList(ViewBag.currency_list, "currencycode", "currencyname")
           , "Select Currency Code", new { @class = "form-control select" })
        @Html.ValidationMessageFor(m => m.currency, null, new { @class = "text-danger" })

    </div>
</div>

drop-down-list-default-value-1.PNG

Select default value for DropDownListFor using ViewBag in ASP.NET MVC


In my controller, I have a list of Currencies stored in ViewBag


public class Currency
{
    public string currencycode { get; set; }
    public string currencyname { get; set; }
}

public ActionResult Index()
{
    List<Currency> list = new List<Currency>();
    list = db.currency.ToList();
    ViewBag.currency_list = list;
    
    return View();
}


You can use the following code to bind the selected value in DropDownListFor in ASP.NET MVC.


        @Html.DropDownListFor(m => m.currency, new SelectList(ViewBag.currency_list, "currencycode", "currencyname", "USD")
           , "Select Currency Code", new { @class = "form-control select" })

If you want "USD" to be selected by default then use the selectedValue property of the SelectList item. You have to use this overload and specify the selectedValue property which you want to set selected.


drop-down-list-default-value-2.PNG

drop-down-list-default-value-3.PNG

html.dropdownlistfor default value SelectList(ViewBag