c# - How to use Display Text property in SelectList -
is there better way of using value
, text
properties of selectlist i'm doing in following view? feel i'm doing work should be.
note: i'm aware of other ways of using dropdowns value
, text
. question related on how achieve same while using selectlist
... var customerslist = _context.customers.select(c => new selectlistitem { value = c.lastname, text = c.fullname }); myviewmodel.lstcustomers = new selectlist(customerslist , "value", "text"); ... return view(myviewmodel);
the htmlhelper
methods generating <select>
element (@html.dropdownlistfor()
etc) expect ienumerable<selectlistitem>
1 of parameters, therefore lstcustomers
should ienumerable<selectlistitem>
public ienumerable<selectlistitem> lstcustomers { get; set; }
you first line of code
var customerslist = _context.customers.select(c => new selectlistitem { value = c.lastname, text = c.fullname });
is generating that, required is
myviewmodel.lstcustomers = customerslist;
you use of new selectlist(customerslist , "value", "text");
creating identical ienumerable<selectlistitem>
first 1 , unnecessary overhead. (selectlist
is ienumerable<selectlistitem>
, wrapper around provide constructors generate collection).
if want use selectlist
constructor change code to
var customerslist = _context.customers; myviewmodel.lstcustomers = new selectlist(customerslist , "lastname", "fullname");
both generate same output. difference between methods selectlist
constructor uses reflection determine properties use options value , display text, fractionally slower, , uses 'magic strings' not typed. benefit little less verbose.
Comments
Post a Comment