如何创建从MVC3 LINQ查询一个DropDownList? [英] How to create a DropDownList from a LINQ query in MVC3?
问题描述
我需要知道我怎么能创建一个下拉列表,重新present所有类别在我的类别表。
I need to know how I could create a drop down list to represent all the categories in my "Categories" table.
我已经提取的名称和每个类别我需要的值,用这个LINQ查询:
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;
我可以通过这个Q我的看法是这样的:
在控制器:
I can pass this "Q" to my view like this : In Controller :
return View(Q);
和在视图:
@model IEnumerable<MyAppName.Models.Category>
但我不知道如何使用 @ html.DropDownListFor()
来使一个不错的下拉列表缩小模型。 :|
But I have no idea how to use @html.DropDownListFor()
to make a darn good drop down list out of the model. :|
PLUS:
我可以做一个的SelectList
从查询Q是这样的:
I could make a SelectList
from the query "Q" like this :
var category_list = new SelectList(Q, "CAT_ID", "CAT_Name");
BUT 我不知道如何创建一个下拉列表(不使用 ViewBag
来传递 category_list
从一个简单的观点)的SelectList
,或者:|
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 ? :/
推荐答案
要使用DropDownListFor你要么必须有具有的SelectList或数据做出选择列表出来的模型和属性来存储的价值选择下拉或使用ViewBag传递category_list。所以,你可以去...
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")
注:我通常不美元的C#C $ç所以我不能保证语法是完全正确的。
Note: I don't typically code in C# so I can't guarantee the syntax is exactly right.
这篇关于如何创建从MVC3 LINQ查询一个DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!