Search code examples
c#visual-studiorazorasp.net-core-mvcrazor-pages

Razor Html.DropDownListFor automatically set the selected value


I am new to Razor, I pass dropdown list as a viewbag and another values, when drop down list show in web it has selected values but i haven't set the any selected value, I think I use same name in viewbag value and dropdownlist value,it can be happen?

This is the viewbag,here i set the values and drop downlist:

ViewBag.GlobalInstance = globalInstance;
ViewBag.LegislativeCode = legislativeCode.Trim();
ViewBag.Legislatives = new SelectList(legislativeEntities, "LegislativeCode", "LegislativeName");

This is frontend code:

@if (ViewBag.GlobalInstance == true)
{
        <div class="col-xs-5 hcm-form_controller mandatory gap" >
            <label for="LegislativeCode" class="w-100" mi-resourcekey="atr-LegislativeCode" >Legislative Entity</label>
            @Html.DropDownListFor(m => m.LegislativeCode, ViewBag.Legislatives as SelectList, "--- Select ---", new { @class = "calc-w-100" })
        </div>
}

Solution

  • It seems that the page model has a value for LegislativeCode,

    m => m.LegislativeCode
    

    so when there is a same LegislativeCode in the ViewBag.Legislatives, this option will be selected.