MVC Dropdownlists - How to Set Dummy Values
This is kind of a two parter:
1) Where should I be feeding my DDL's from? Right now I have List set in my viewmodel. I've seen a lot of people set the lists in the ViewData[]. Is that what I s开发者_如何学编程hould be doing, and why?
I've noticed that the DDL values are not retained in the HttpPost and I have to reset them in the view model. If I use ViewData[] I am assuming this is not necessary?
2) I am populating my DDL's from LinqToSQL by
new SelectList(dataContext.Products.ToList(),"ID","Name");
How should I add a dummy field like "--Select a Product--" val="-1"?
There are a huge variety of methods to deal with drop down list data. I personally use filters to inject collections into view models (90% of the time at least), but I won't go into that there. You can use the Insert method to add a placeholder item.
var options = dataContext.Products.Select(p => new OptionItem(p.Id, p.Name)).ToList();
options.Insert(0, new OptionItem(-1, "--Select a Product--"));
// now use the options collection for the drop down list source
Note I did a projection from Product to OptionItem because you don't really need to query for the entire Product object if you just want two fields.
精彩评论