Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC multiple fields in dropdown list

I have a dropdown list generated by a create scaffold that shows the first name of clients from the data base.

the view looks like this

 <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>

and the controller looks like this

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

Is there a way to add "LastName" to the dropdown list as well so more than one field is being shown?

like image 672
Sepehr Sobhani Avatar asked Aug 16 '14 06:08

Sepehr Sobhani


1 Answers

I know that this is an old question but I had the same problem and found this page before eventually figuring it out myself.

Here is the correct answer:

Controller:

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

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

View:

@Html.DropDownListFor(model => model.ClientID, (SelectList)ViewBag.ClientsList, new { @class = "form-control" })
like image 144
JasonBluefire Avatar answered Oct 25 '22 03:10

JasonBluefire