首页 > 解决方案 > Razor Html.DropDownListFor 自动设置选中值

问题描述

我是 Razor 的新手,我将下拉列表作为 viewbag 和另一个值传递,当下拉列表在 web 中显示时它具有选定的值但我没有设置任何选定的值,我想我在 viewbag 值和下拉列表中使用相同的名称值,这可能发生吗?

这是viewbag,在这里我设置了值和下拉列表:

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

这是前端代码:

@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>
}

标签: c#visual-studiorazorasp.net-core-mvcrazor-pages

解决方案


看来页面模型对LegislativeCode有价值,

m => m.LegislativeCode

因此,当 中存在相同时LegislativeCodeViewBag.Legislatives将选择此选项。


推荐阅读