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
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
ViewBag.Title = “ddl“;
}
Now you can run Project And see the Output as following.
SEE MORE
- Auto Refresh Partial View in ASP.NET MVC
- What is ASP.NET Core
- Difference between TempData keep() And Peek() in Asp.Net MVC
- Difference between viewbag,viewdata and tempdata in asp.net mvc
- ASP.NET MVC With AngularJS
- Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC
- MVC CRUD Operations Using Entity Framework
- Search Functionality in ASP.NET MVC
- How to create a User Registration page using asp.net mvc
- Store Multiple Checkbox state from cookie using Jquery
- Cascading Dropdownlist using Ajax in Asp.Net Mvc with city state country
- Insert, Update, Delete In GridView Using ASP.Net C#
- Binding Dropdownlist With Database In Asp.Net MVC
- Search and Filter data in Gridview using Asp.net MVC
- Select Insert, Update And Delete With ASP.NET MVC
- Display Data in GridView Using Asp.net MVC
- Validation in ASP.NET MVC Razor view
- CRUD Operation Using 3-Tier Architecture In ASP.NET
- How to get Connection String from Web.Config in Asp.Net C#
- Login page using 3-Tier Architecture in ASP.Net
- Asp.Net Image Upload in 3-Tier Architecture and store in sql database
24 Comments