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?
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With