Binding Dropdownlist With Database In Asp.Net MVC

In this tutorial we have learn about how to Binding Dropdownlist With Database In Asp.Net MVC,here we have first getting data from database and using viewbage we can pass this data to razor view.

Step 1 : first we need to create sql database with table name tbl_user

Binding Dropdownlist With Database In Asp.Net MVC

Step 2 : Now you can add model class as below DAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class DAL
{
public int id { get; set; }
[Required]
public string Name { get; set; }
public string City { get; set; }
public string Education { get; set; }

public SqlConnection con = new SqlConnection(@”Data Source=(LocalDB)\v11.0;\Database1.mdf;Integrated Security=True”);

public DataSet Binddl(DAL da)
{
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(“select Name from tbl_user“,con);
adp.Fill(ds);
return ds;

}
}
}

Step 4: Now add code in controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Data;
using System.Data.SqlClient;
namespace MvcApplication1.Controllers
{
public class ABCController : Controller
{
//
// GET: /ABC/

public ActionResult Index()
{
return View();
}

public ActionResult ddl(DAL da)
{
DataSet ds = da.Binddl(da);
ViewBag.fname = ds.Tables[0];
List<SelectListItem> lst = new List<SelectListItem>();
foreach (System.Data.DataRow dr in ViewBag.fname.Rows)
{
lst.Add(new SelectListItem { Text = @dr[“Name“].ToString(), Value = @dr[“Name“].ToString() });
}
ViewBag.Name = lst;
return View();
}

}

}

Step 5: Now you can View as following in ddl.cshtml

@model MvcApplication1.Models.DAL@{
ViewBag.Title = “ddl“;
}
@Html.DropDownList(“Name“, ViewBag.Name as SelectList)

Now you can run Project And see the Output as following.

Binding Dropdownlist With Database In Asp.Net MVC

SEE MORE

21 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *