How to create a DropDownList from a LINQ query in MVC3?

亡梦爱人 提交于 2019-12-06 10:46:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!