Thursday, 22 September 2016

How to bind Country, State, City Dropdownlist in mvc using ajax



Introduction:
I will explain how to bind Country, State City Dropdown list in Asp.net MVC using Ajax call. I used Ado.net for database connection and controller method using Jquery method
Description:
Step1: Firstly we create fallowing three tables in database
Country table:  tbl_country
CREATE TABLE [dbo].[tbl_Country] (
    [Country_id]   INT           IDENTITY (1, 1) NOT NULL,
    [Country_Name] NVARCHAR (50) NULL,
    CONSTRAINT [PK_tbl_Country] PRIMARY KEY CLUSTERED ([Country_id] ASC)
);
State table: tbl_state
CREATE TABLE [dbo].[tbl_state] (
    [State_id]   INT            NOT NULL,
    [Country_id] INT            NULL,
    [State]      NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_tbl_state] PRIMARY KEY CLUSTERED ([State_id] ASC)
);

City Table: tbl_city
CREATE TABLE [dbo].[tbl_city] (
    [City_id]  INT            NOT NULL,
    [State_id] INT            NULL,
    [City]     NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_tbl_city] PRIMARY KEY CLUSTERED ([City_id] ASC)
);

Step2: Now we create Database_Access_Layer as fallowing
 

Step3: Now we write fallowing code in db.cs class in database_Access_layer folder

public class db
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        // Get All Country
        public DataSet Get_Country()
        {
            SqlCommand com = new SqlCommand("Select * from tbl_Country", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        //Get all State
        public DataSet Get_State(string country_id)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_state where Country_id=@catid", con);
            com.Parameters.AddWithValue("@catid", country_id);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        //Get all City
        public DataSet Get_City(string state_id)
        {
            SqlCommand com = new SqlCommand("Select * from tbl_city where State_id=@stateid", con);
            com.Parameters.AddWithValue("@stateid", state_id);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
    }
Step 4: Add Home controller in controller folder

Step5: Write fallowing code in HomeController.cs

public class HomeController : Controller
    {
      
        Database_Access_Layer.db dblayer = new Database_Access_Layer.db();

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

        public void Country_Bind()
        {
            DataSet ds = dblayer.Get_Country();
            List<SelectListItem> coutrylist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                coutrylist.Add(new SelectListItem { Text = dr["Country_name"].ToString(), Value = dr["Country_id"].ToString() });
            }
            ViewBag.Country = coutrylist;
        }

        public JsonResult State_Bind(string country_id)
        {
            DataSet ds = dblayer.Get_State(country_id);
            List<SelectListItem> statelist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                statelist.Add(new SelectListItem { Text = dr["State"].ToString(), Value = dr["State_id"].ToString() });
            }
            return Json(statelist, JsonRequestBehavior.AllowGet);
        }

        public JsonResult City_Bind(string state_id)
        {
            DataSet ds = dblayer.Get_City(state_id);
            List<SelectListItem> citylist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                citylist.Add(new SelectListItem { Text = dr["City"].ToString(), Value = dr["City_id"].ToString() });
            }
            return Json(citylist, JsonRequestBehavior.AllowGet);
        }

    }


Step6: Add Index view in view folder

Step7: Write fallowing Ajax method and html in Index.cshtml file

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/script/jquery-1.7.1.min.js"></script>
    <script>

        $(document).ready(function () {
            $("#Country").change(function () {
                var id = $(this).val();
                $("#state").empty();
                $.get("State_Bind", { country_id: id }, function (data) {
                    var v = "<option>---Select---</option>";
                    $.each(data, function (i, v1) {
                        v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
                    });
                    $("#state").html(v);
                });
            });

            $("#state").change(function () {
                var id = $(this).val();
                $("#city").empty();
                $.get("City_Bind", { state_id: id }, function (data) {
                    var v = "<option>---Select---</option>";
                    $.each(data, function (i, v1) {
                        v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
                    });
                    $("#city").html(v);
                });
            });
        });
    </script>
</head>
<body>
    <div>
        <div>
            @Html.DropDownList("Country", null, "---Select Country----")
        </div>
        <div>
            <select id="state"></select>
        </div>
        <div>
            <select id="city"></select>
        </div>
    </div>
</body>
</html>

Step7: Output of above example
Download Full Source Code Here:

4 comments:

Ads Inside Post