Asp.net MVC下拉列表中的多个字段

时间:2014-08-16 06:24:02

标签: c# asp.net asp.net-mvc drop-down-menu

我有一个创建脚手架生成的下拉列表,显示数据库中客户端的名字。

视图看起来像这样

 <div class="form-horizontal">
    <h4>ProgramClientTbl</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.ClientId, "ClientId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ClientId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ClientId, "", new { @class = "text-danger" })
        </div>
    </div>

,控制器看起来像这样

        public ActionResult Create()
    {
        ViewBag.ClientId = new SelectList(db.ClientsTbls, "Id", "FirstName"); 
        ViewBag.ProgramId = new SelectList(db.ProgramTbls, "Id", "Program");
        return View();
    }

有没有办法添加&#34; LastName&#34;到下拉列表中也显示了多个字段?

4 个答案:

答案 0 :(得分:4)

我知道这是一个老问题,但我遇到了同样的问题,并在最终自己搞清楚之前找到了这个页面。

这是正确答案:

控制器:

var clients = db.ClientsTbls
    .Select(s => new
        {
        Text = s.FirstName + " " + s.LastName,
        Value = s.clientId
    })
    .ToList();

ViewBag.ClientsList = new SelectList(clients, "Value", "Text");

查看:

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

答案 1 :(得分:4)

您必须更新模型:

public class Teacher
{   //...
    public string PaternalName { get; set; }
    public string MaternalName { get; set; }
    public string Name { get; set; }
    //... your others columns.  Add something like:
    public string FullName
    {
        get
        {
            return String.Format("{0} {1}, {2}", PaternalName, MaternalName, Name);
        }
    }
    ...
}

那你只需要:

ViewBag.CodigoDocente = new SelectList(db.Docente,“IDteacher”,“FullName”);

答案 2 :(得分:1)

假设您有FirstNameLastName属性

var clients = (from c in db.ClientsTbls
  select new SelectListItem { 
    Text = m.FirstName + " " + m.LastName,
    Value = m.ID.ToString()
  });
ViewBag.ClientsList = new SelectList(clients); // but better to assign this to a property in your view model

然后在你看来

@Html.DropDownLstFor(m => m.ClientID, (SelectList)ViewBag.ClientList, new { @class = "form-control" })

答案 3 :(得分:0)

对不起,我无法对Jason和Stephen回答发表评论,但是我试图结合JasonBlufire和Stephen Muecke的回答,并且奏效了。

101889