How to Bind two Drop-Downs From two Different Tables

Total Post:52

Points:366
C#  Mvc4 
C#
 778  View(s)
Ratings:
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.

 

Thanks,

  1. Post:52

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

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

    Model

    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>
    <html>
    <head>
    </head>
    <body>
        @using (Html.BeginForm())
        {
            @Html.DropDownList("Customer", new SelectList(Model.Customerlist, "Value", "Text"))
            @Html.DropDownList("Product", new SelectList(Model.Productlist, "Value", "Text"))
        }
    </body>
    </html>

     

    Hope this will helps you..


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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!