Populate DropDownList using MVC 4 & Entity Framework

前端 未结 4 738
礼貌的吻别
礼貌的吻别 2020-12-16 22:04

I\'m developing MVC4 & Entity Framework Application.I wanted to populate DropDownList,I wanted to bind Category List to Dodropdown list

IRepository Code

相关标签:
4条回答
  • 2020-12-16 22:11

    Using the ViewBag (as some have suggested in other answers/comments) to get data from your controller to view is generally seen as a code smell.

    Your ViewModel should ideally contain all of the data you need for your view. So use your controller to populate this data on a property of your ViewModel:

    SelectList ProductTypes { get; set; }
    

    Then bind your dropdown to this value

    @Html.DropDownListFor(m => m.ProductType, Model.ProductTypes)
    

    You can find this same answer given on this post.

    0 讨论(0)
  • 2020-12-16 22:13

    Very simple Code step by step 1) In Entity Framework Class

    var productsList = (from product in dbContext.Products
                         select new ProductDTO
                         {
                           ProductId = product.ProductId,
                           ProductName = product.ProductName,
                           }).ToList();
    

    2) In Controller

    ViewBag.productsList = new EntityFrameWorkClass().GetBusinessSubCategoriesListForDD();
    

    3) In View

    @Html.DropDownList("Product_ProductId", new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })
    

    OR

    @Html.DropDownListFor(m=>m.Product_ProductId, new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })
    
    0 讨论(0)
  • 2020-12-16 22:15

    You could do this:

    @Html.DropDownListFor(x => x.IdCategory, ViewBag.Categories)
    

    But I would recommend you to avoid ViewBag/ViewData and profit from your viewmodel:

    public ActionResult AddProduct()
    {
        var model = new TestModel();
    
    //This is just a example, but I advise you to turn your IList in a SelectListItem, for view is more easy to work. Your List Categories will be like this hardcoded:
    
    model.ListCategories= new SelectList(new[]
    {
        new { Value = "1", Text = "Category 1" },
        new { Value = "2", Text = "Category 2" },
        new { Value = "3", Text = "Category 3" },
    }, "Value", "Text");
    
    return View(model);
    

    }

    and in the view:

    @Html.DropDownListFor(x => x.IdCategory, Model.ListCategories)
    

    I hope I have helped

    0 讨论(0)
  • 2020-12-16 22:31

    How about using ViewBag?

    View

    <label for="ProductType">Product Type</label>
       @Html.DropDownListFor(m => m.ProductType,ViewBag.ListOfCategories)
    

    Controller

    public ActionResult AddProduct()
    {
        ViewBag.ListOfCategories = GetCategory();
        return View();
    }
    
    0 讨论(0)
提交回复
热议问题