问题
I need to know how I could create a drop down list to represent all the categories in my "Categories" table.
I have already extracted the names and the values of each category I need, using this LINQ query :
var dbcontext = new LNQ2SQLDataContext();
var Q = from P in dbcontext.Categories
where P.SUB_CAT == null
select P;
I can pass this "Q" to my view like this : In Controller :
return View(Q);
And in the View :
@model IEnumerable<MyAppName.Models.Category>
But I have no idea how to use @html.DropDownListFor()
to make a darn good drop down list out of the model. :|
PLUS:
I could make a SelectList
from the query "Q" like this :
var category_list = new SelectList(Q, "CAT_ID", "CAT_Name");
BUT I don't know how to create a drop down list (without using ViewBag
to pass the category_list
to the view) from a simple SelectList
, either :|
I searched through as many blogs and websites as I could. But they didn't have the solution for my problem. I only got more and more confused!
So can anybody help please ? :/
回答1:
To use DropDownListFor you'll either have to have a model that has a SelectList or data to make a selectlist out of and a property to store the selected value of the dropdown OR use the ViewBag to pass the category_list. So you can go with...
Public Class MyViewModel
{
Public Integer SelectedCategory { get; set; }
Public SelectList Categories { get; set; }
}
Public Class ItemsController : Controller
{
Public ActionResult Index()
{
var dbcontext = new LNQ2SQLDataContext();
var Q = from P in dbcontext.Categories
where P.SUB_CAT == null
select P;
var vm = new MyViewModel();
vm.Categories = new SelectList(Q, "CategoryID", "Name");
return View(vm);
}
[HttpPost()]
Public ActionResult Index(MyViewModel vm)
{
var theSelectedCategory = vm.SelectedCategory;
}
}
The view would be...
@model MyViewModel
@Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select Category")
Note: I don't typically code in C# so I can't guarantee the syntax is exactly right.
来源:https://stackoverflow.com/questions/11758747/how-to-create-a-dropdownlist-from-a-linq-query-in-mvc3