Yasser Bahnasy Yasser Bahnasy - 1 year ago 72
ASP.NET (C#) Question

How select data from Multi Database in MVC4

I have two tables. First table

contains the columns
product id
. The second table
contains columns
Department id

I want to create a page to insert to Products details in Product table and I want a combo box should be populated with Departments name at this page.

Answer Source

Although your question is not clear to us. But somehow i figured it out what you want..

Model classes

public class Product
    public int ProductId { get; set; }

    public string ProductName { get; set; }

public class Departments
    public int DepartmentID{get;set;}
    public string DepartmentName {get;set;}


public class HomeController : Controller
    public ActionResult Index()
          List<Departments> deps = new List<Departments>();

        deps.Add(new Departments() {DepartmentID=1, DepartmentName="IT"});
        deps.Add(new Departments() { DepartmentID = 2, DepartmentName = "HR" });

        ViewBag.lstDeps = deps;

        return View(new Product());


    @model HelloWorldMvcApp.Product
    Layout = null;

   IEnumerable<HelloWorldMvcApp.Departments> CDrop = ViewBag.lstDeps;

        List<SelectListItem> selectList = new List<SelectListItem>();
        foreach (var c in CDrop)
            SelectListItem i = new SelectListItem();
            i.Text = c.DepartmentName.ToString();
            i.Value = c.DepartmentID.ToString();

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
        <meta charset="utf-8">


        <div class="container">
            <div class="col-md-6 col-md-offset-3">
                <h1>Hello Stranger</h1>

                @Html.DropDownList("DEpartments", new SelectList(selectList, "Value","Text"))

                @using (Html.BeginForm())
                    <div class="form-group">
                        @Html.LabelFor(m => m.ProductName)
                        @Html.TextBoxFor(model => model.ProductName, new {@class="form-control"}) 





        <!-- JS includes -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

Working Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download