【问题标题】:How to take FirstName and LastName in DropDown List如何在下拉列表中获取名字和姓氏
【发布时间】:2017-04-03 13:17:52
【问题描述】:

在控制器中,我有这段代码,此时我有下拉列表,仅用于名字。

代码在这里:

ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "firstname");

现在我需要这样的代码:

ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", ("firstname" + "lastname"));

怎么做?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 model-view-controller


    【解决方案1】:

    您的 tbl_patnici 课程

    public class tbl_patnici
    {
       public int pID { get; set; }
       public string firstname { get; set; }
       public string lastname { get; set; }
       //[NotMapped] If you use entityframework then you must use NotMapped attribute.
       public string fullname { get { return this.firstname + " " + this.lastname; } }
    }
    
    ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "fullname");
    

    【讨论】:

    • 感谢大家,但@Murat ÖNER 的回答对我来说是最好的。谢谢
    【解决方案2】:

    我建议您不要直接绑定到数据库源,而是绑定到您自己的具有所需属性的 IEnumerable。我经常有一个可重用的“ListItem”类,它具有 ID 和 Text 属性,然后使用函数用我想要的数据填充列表。

    例如:

    创建一个新类:

    public class ListItem
    {
        public int ID { get; set; }
        public string Text { get; set; }
    }
    

    创建一个辅助函数:

    public List<ListItem> GetList()
    {
        // get "db" here.
        return db.tbl_patnici.Select(x => new ListItem {
            ID = x.pID,
            Text = x.firstname + " " + x.lastname
        });
    }
    

    这样称呼它:

    ViewBag.patnikID = new SelectList(GetList(), "ID", "Text");
    

    【讨论】:

      【解决方案3】:

      你可以检查一下:

      @Html.DropDownListFor(model => model.pID, new SelectList(db.tbl_patnici, "pID", Model.firstname + " " + Model.lastname, Model.pID), new { style = " width:260px" })
      

      【讨论】:

        猜你喜欢
        • 2021-01-04
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多