简体   繁体   中英

Is there a simple way to display both the value and text fields in a drop-down list in MVC (razor)?

I have a simple view dropdownlist in razor,

@Html.DropDownList("Client_Id", null, htmlAttributes: new { @class = "form-control" })

and for the controller I have the following viewbag,

ViewBag.Client_Id = new SelectList(db.ClientMetadatas, "Client_Id", "Name");

Now is it possible to have a simple way, to display the client_id along with the Name in the dropdown ?

I would suggest creating an anonymous class using the Select extension method.

ViewBag.Client_Id = new SelectList(db.ClientMetadatas.Select(x => new { ClientId = x.Client_Id, CombinedProperty = x.Client_Id.ToString() + " " + x.Name }).ToList(), "ClientId", "CombinedProperty");

Please let me know if this was able to assist you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM