【问题标题】:Mvc DropdownList default selected value by ViewBagViewBag 的 Mvc DropdownList 默认选择值
【发布时间】:2019-06-05 10:12:15
【问题描述】:

我已经填充了一个 viewbag 并将一个下拉列表绑定到它..如下所示

var countrylist = ctx.Countries.ToList();
ViewBag.countrylist = new SelectList(countrylist, "ID", "Name",2);

@Html.DropDownList("countrylist", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")

上面我想默认选择 countrylist 的第二项,所以我提到了值“2”作为 ViewBag countrylist 重载的最后一个参数。 但默认情况下它不会选择该项目。

但是,如果我将下拉列表名称更改为如下所示的其他名称

@Html.DropDownList("countrylist12345", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")

那么它会默认选择国家列表中的第二项。

请解释为什么会这样?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5


    【解决方案1】:

    您的整个视图很可能是使用某些模型进行强类型化的

    @model YourNamespace.SomeModel
    

    这个模型有一个字段countrylist,它有一些值,默认可能是0。并且由于该字段的名称与下拉菜单本身的名称相同,因此该字段的值就是下拉菜单用来确定默认选择的值。更改下拉列表的名称后,连接就消失了。

    您可以做的是确保在countrylist 字段中为您用于强类型化视图的模型分配了一些值。例如,在控制器内部:

    SomeModel model = new SomeModel();
    model.countrylist = 2;
    return View(model);
    

    【讨论】:

    • 不,兄弟,我的观点不受严格约束。我只是在练习下拉列表,发现这种不稳定的行为我不知道为什么会这样。是某种约定还是什么?
    猜你喜欢
    • 2013-10-19
    • 2019-12-15
    • 2017-06-01
    • 1970-01-01
    • 2013-09-17
    • 2016-07-12
    • 2014-10-05
    • 2011-03-17
    • 1970-01-01
    相关资源
    最近更新 更多