How to Bind two Drop-Downs From two Different Tables

Total Post:52

C#  Mvc4 
 966  View(s)
Rate this:

I have two dropdownlist in the page. 

how to bind these two dropdownlist from database 

One Dropdownlist has to bind from One Table and Another Dropdownlist is to bind from another table.



  1. Post:52

    Re: How to Bind two Drop-Downs From two Different Tables

    You can use ViewModel to load two dropdownlist from multiple tables like below


    Create a ViewModel in your model folder

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    namespace Testing.Models
        public class MultipleTableViewModel
            public IEnumerable<SelectListItem> Customerlist { get; set; }
            public IEnumerable<SelectListItem> Productlist { get; set; }

     Now load the ViewModel with data in controller

       public ActionResult Index()
                AdventureWorksEntities db = new AdventureWorksEntities();
                //Get the Customer Details
                var Customerresult =db.Customers.Take(10).Select(c => new SelectListItem
                    Value = c.PersonID.ToString(),
                    Text = c.StoreID.ToString()
                //Get the Product Details
                var Productresult =db.Products.Take(10).Select(c => new SelectListItem
                    Value = c.ProductID.ToString(),
                    Text = c.Name.ToString()
                //Assign those resuLts to ViewModel
                var model = new MultipleTableViewModel
                    Customerlist = Customerresult,
                    Productlist = Productresult
                //Pass the model to View
                return View(model);

    view code

    @model  Testing.Models.MultipleTableViewModel
    <!DOCTYPE html>
        @using (Html.BeginForm())
            @Html.DropDownList("Customer", new SelectList(Model.Customerlist, "Value", "Text"))
            @Html.DropDownList("Product", new SelectList(Model.Productlist, "Value", "Text"))


    Hope this will helps you..

      Modified On Apr-11-2018 10:55:58 PM