Asp.net MVC multiple fields in dropdown list
14,437
Solution 1
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" })
Solution 2
You have to update your model:
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);
}
}
...
}
THEN YOU ONLY HAVE TO:
ViewBag.CodigoDocente = new SelectList(db.Docente, "IDteacher", "FullName");
Solution 3
sorry i can't add comment on Jason and Stephen Answer, but I tried to combine answers from JasonBlufire and Stephen Muecke, and it's worked.
var clients = (from c in db.ClientsTbls
select new SelectListItem {
Text = m.FirstName + " " + m.LastName,
Value = m.ID.ToString()
});
ViewBag.ClientsList = new SelectList(clients,"Value", "Text");
Author by
Sepehr Sobhani
Updated on June 14, 2022Comments
-
Sepehr Sobhani almost 2 years
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?
-
Admin about 8 yearsViewBag.TeacherCode = new SelectList(db.Teacher, "IDteacher", "FullName");
-
Admin about 8 years
-
Nacho about 8 yearsYou can add the corrections you mention here in your comments inside your answer using the "edit" link on the lower left corner of the answer.