Help with asp.net mvc SelecList, Html.dropdownList and linqtosql
I have 开发者_StackOverflowusers table, it has id, name last name
I have a linq to sql class
I want a dropdownlist that has id for value and has NAME AND LASTNAME for text.... how can i do this?
ViewData["User_Id"] = new SelectList(UsersRepository.GetAll(), "Id", "Name");
works just fine but I want
ViewData["User_Id"] = new SelectList(UsersRepository.GetAll(), "Id", "Name "+" Last_Name");
which doesnt work... help please
Try using some good old LINQ.
var data = from u in UsersRepository.GetAll()
select new {
Id : u.Id,
Name : string.Concat(u.Name, u.LastName)
};
ViewData["User_Id"] = new SelectList(data, "Id", "Name");
This control uses reflection to find the right properties for dataText and dataValue. You will not be able to add the properties together.
You can create an anonymous type though.
Assuming the collection from the database looks something like the following:
var testModelCollection = new List<TestModel>() {
new TestModel() { Id = 1, Name = "Bob", LastName = "Smith" },
new TestModel() { Id = 2, Name = "Jack", LastName = "Thompson" }
};
var changedModelCollection = from t in testModelCollection
select new {
Id = t.Id,
FullName = t.Name + " " + t.LastName
};
ViewData["User_Id"] = new SelectList(changedModelCollection, "Id", "FullName");
Your definition for the DropDownList in your view will look something like this:
<%= Html.DropDownList("Username", (SelectList)ViewData["User_Id"], "Select a User") %>
精彩评论