[MVC4- based database access] from display in DropDownList

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Starting with MVC4, the following are the basis of the study notes!

The finished result like this, the data source is already some Database.


1.Controller

public ActionResult Index()
        {

            SqlConnection DbErp = new SqlConnection(ErpString); //Create a database connection
            SqlCommand cmd = new SqlCommand("select dep,name from dept",DbErp); //Enter the SQL command
            DbErp.Open(); //Open database connectivity

            var reader = cmd.ExecuteReader(); //Remove the result set

            List<SelectListItem> depts = new List<SelectListItem>();

            while(reader.Read()){ //Note read data written to the List
                //(0)=dep ; (1)=name
                depts.Add(new SelectListItem { Text = reader.GetString(1), Value = reader.GetString(0)});
            }

            DbErp.Close(); //Close the database connection

            ViewBag.DeptType = depts;

            return View();
        }

2.View

<h2>Repair requisition</h2>

<p>
    @Html.Label("DeptType","Application Department")
    @Html.DropDownList("DeptType")
</p>

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

Posted by Aimee at November 14, 2013 - 7:32 AM