How would I generate a select list, where the text field, is made up of two or more text columns, eg: Where I have a Description and Rate field in my database, I want to combine these to show:
Large--£200
Medium--£150
Small--£100
Controller code is:
var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");
...and my view is (currently):
<div class="editor-field">
@Html.DropDownList("StandID", "--Select--")
</div>
...but the "Description" + "-- £" + "Rate"); won't run:
DataBinding: 'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4' does not contain a property with the name 'Description--£Rate'.
Thanks for any help,
Mark
You can create a partial Model class
Then in your View
You could create a new anonymous class using a simple LINQ projection, and then use the
SelectList(IEnumerable, string, string)
constructor overload to specify the value and text fields to be used for the<option>
elements i.e.:Edit
In C#6 and later, string interpolation makes for better reading than
string.Format
If you project to a strong
ViewModel
class name (instead of to an anonymous class), you will undoubtedly want to replace the magic strings with the safety of thenameof
operator:I did this by modifying my View Model, here are my code:
The View Model
The Controller
The View
The result:
The Format of the constructor that you are using is SelectList(IEnumerable items, string dataValueField, string dataTextField).
So when you use it the way you have you are actually telling it to bind to the TextField called "Description-- £Rate" and if this is not what the field is called coming in the from the DB it won't know what you are indicating.
Either of the two methods described above will work as long as the value you have in your dataValueField matches the name of the property you put the Value in and the dataTextField matches the property name of where you put the Text, perhaps a mix of the two solutions above. (Only because I prefer lambda expressions over linq.) and using a selectlist item prevents it from have to do a ToList on the collection after the transform. you are actually creating the objects that naturally bind to a select list.
You also may want to put in checks on the description or rate to make sure they aren't empty before putting them into the list