-->

如何创建从MVC3 LINQ查询一个DropDownList?(How to create a Dr

2019-09-20 14:20发布

我需要知道我怎么可以创建一个下拉列表来表示我的“类别”表中的所有类别。

我已经提取的名称和每个类别我需要的值,使用这个LINQ查询:

var dbcontext = new LNQ2SQLDataContext();
        var Q = from P in dbcontext.Categories
                where P.SUB_CAT == null
                select P;

我可以通过这个“Q”我的看法是这样的:在控制器:

return View(Q);

并在视图:

@model IEnumerable<MyAppName.Models.Category>

但我不知道如何使用@html.DropDownListFor()做一个不错的下拉列表缩小模型。 :|

加:

我可以做一个SelectList从查询“Q”是这样的:

var category_list = new SelectList(Q, "CAT_ID", "CAT_Name");

我不知道如何创建一个下拉列表(不使用ViewBag的传递category_list到视图)从一个简单SelectList ,或者:|

我搜索通过尽可能多的博客和网站,我可以。 但是,他们并没有对我的问题的解决方案。 我只得到了越来越糊涂了!

因此,任何人可以帮助吗? :/

Answer 1:

要使用DropDownListFor你要么必须有具有的SelectList或数据做出选择列表的出来的,并保存下拉列表中选择的值或使用ViewBag传递category_list属性的模型。 所以,你可以去...

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;
    }
}

视图是...

@model MyViewModel
@Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select Category")

注:我通常不会在C#代码,所以我不能保证语法是完全正确的。



文章来源: How to create a DropDownList from a LINQ query in MVC3?