【问题标题】:DropDownList not selected in Edit page编辑页面中未选择下拉列表
【发布时间】:2015-03-25 15:36:49
【问题描述】:

我使用“带有视图的 MVC 5 控制器,使用实体框架”创建了控制器,并将“编辑”视图中的“DropDownList”代码修改为

@Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.prdepno, new { @class = "form-control" })

在Controller中使用ViewBag

personal personal = db.personals.Find(id);

ViewBag.prdepno = new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);

没有错误,但未选择下拉列表

我从Adding a css class to select using @Html.DropDownList() 查找 和其他问题尝试这样做,但它不起作用(对我来说)

我不知道该怎么做 (对不起,在我的交流中。)

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 不要为模型属性和 ViewBag SelectList 属性使用相同的名称
  • 感谢@JohnSaunders 编辑,这是我的第一篇文章
  • 感谢@StephenMuecke,它有效..(我没有注意到这里的细节。)
  • 请注意,如果您使用DropDownListFor() 绑定到属性,则不需要SelectList 的最后一个参数。所选选项基于模型属性的值,因此被忽略。

标签: c# asp.net asp.net-mvc-5 viewbag dropdownlistfor


【解决方案1】:

我认为您需要更改 ViewBag 对象的名称

personal personal = db.personals.Find(id);

ViewBag.DwPrdeps= new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);

之后在您的视图中使用ViewBag.DwPrdeps

@Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.DwPrdeps, new { @class = "form-control" })

【讨论】:

  • 谢谢@MANISH,我注意到了更多
【解决方案2】:

尝试使用此代码它可以正常工作

代码生成/模型

public class CityList
    {
        public string city { get; set; }
    }
public static IEnumerable<SelectListItem> GetCity()
{
    IList<SelectListItem> items = new List<SelectListItem>
    {
        new SelectListItem{Text = "Dhaka", Value = "dhk" },
        new SelectListItem{Text = "Chittagong", Value = "CTG" }
    };
    return items;
}

为创建

ViewBag.city = new SelectList(GetCity(), "Text", "Value");

@Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { @class = "form-control select2", required = "required" })

用于编辑

ViewBag.city = new SelectList(GetCity(), "Text", "Value",model.city);

@Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { @class = "form-control select2", required = "required" })

你可以试试这个,效果很好。

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2020-02-27
    • 1970-01-01
    • 2014-05-24
    相关资源
    最近更新 更多