MVC SelectList combining multiple columns in text field

前端 未结 5 1507
遇见更好的自我
遇见更好的自我 2020-12-04 19:12

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 com

5条回答
  •  借酒劲吻你
    2020-12-04 19:36

    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 elements i.e.:

    var stands = 
      db.Stands
        .Where(s => s.ExhibitorID == null)
        .Select(s => new 
         { 
           StandID = s.StandID,
           Description = string.Format("{0}-- £{1}", s.Description, s.Rate) 
         })
        .ToList();
    
    ViewBag.StandID = new SelectList(stands, "StandID", "Description")
    

    Edit

    In C#6 and later, string interpolation makes for better reading than string.Format

       ...
       Description = $"{s.Description}-- £{s.Rate}"
    

    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 the nameof operator:

    ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
    

提交回复
热议问题