I’m experimenting with ASP.NET MVC3 and want to simply populate a dropdown list with data I get from a LINQ2SQL class, like so
controller (I know, Linq doesn’t belong in the controller)
var allUsers = (from u in _userDataContext.Users
select u).ToList();
ViewBag.allUsers = allUsers.ToList();
return View();
view:
<select id="drop_heroes">
@foreach (var u in ViewBag.allUsers)
{
<option value="@u.pk_userid">@u.email</option>
}
</select>
That works fine, but I would like to use Razor @Html.Dropdownlist to create the same dropdown list, but can't find any info to make this work with Linq data.
Then why are you using it in a controller? Anyway, at least it’s fine that you know it.
Here’s an example. As always in an ASP.NET MVC application you start by defining a view model which will represent the data that you need in the view. So in your case you need to display a dropdown so you define a list of users and a selected user id:
then you define a controller action which will populate this view model from your repository and handle it to the view:
and finally you will have a view which will be strongly typed to your view model and use HTML helpers to generate the dropdownlist:
Things to notice:
If you follow these simple rules you will see how much easier your life as an ASP.NET MVC developer will become.