Yasser Bahnasy Yasser Bahnasy - 4 months ago 10
ASP.NET (C#) Question

How select data from Multi Database in MVC4

I have two tables. First table

Product
contains the columns
product id
,
name
and
Department_id
. The second table
Departments
contains columns
Department id
and
name
.

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

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;}
}

Controller

public class HomeController : Controller
{
    [HttpGet]
    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());
    }

View

    @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();
            selectList.Add(i);
        }

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

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

    </head>

    <body>
        <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"}) 

                    </div>

                }

                <br/><br/>

            </div>
        </div>

        <!-- 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>
    </body>
</html>

Working Demo