gpt4 book ai didi

asp.net-mvc - 未选择值的 DropDownList

转载 作者:行者123 更新时间:2023-12-01 23:20:43 25 4
gpt4 key购买 nike

我在编辑页面内使用 DropDownListFor 辅助方法,但我没有运气让它选择我指定的值。我注意到一个similar question在 Stackoverflow 上。建议的解决方法是“在 View 代码中填充 SelectList”。问题是我已经尝试过了,但仍然不起作用。

<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>

我已经设置了一个断点并验证了 model.AddressStateAbbr 的存在(和有效性)。我只是不确定我错过了什么。

最佳答案

经过一个小时的研究,我发现了导致所选内容未设置为 DropDownListFor 的问题。原因是您使用的 ViewBag 的名称与模型的属性相同。

示例

public  class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}

// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

查看

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")

所选选项不会设置为下拉列表,但是当您将 ViewBag 的名称更改为其他名称时,所选选项将显示正确。

示例

ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

查看

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")

关于asp.net-mvc - 未选择值的 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2278056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com