connectseekers.com

Wednesday, 24 September 2014

jQuery Ajax Cascaded DropdownList in Asp.net MVC Using C#.Net

9/24/2014 - By Pranav Singh 0

This article will show you how you can create a cascaded dropdown list by jQuery in asp.net mvc and c#.net. This will show you to create Ajax enabled dropdown list using jQuery.


So for this article first we will create a new asp.net mvc application and in this we will first add a model class file. In this model class file add the below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Models
{
    public class StateMasterModel
    {
        public List<StateMaster> StateMaster { get; set; }
        public SelectList StateList { get; set; }
        public SelectList TehsilList { get; set; }
    }
    public class StateMaster
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
}

After this we will add a controller file into our application and add the below code into our controller class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            StateMasterModel objstatemodel = new StateMasterModel();


            /*For state*/
            StateMaster objStateMaster = new StateMaster();
            objStateMaster.Id = 0;
            objStateMaster.StateName = "Select State";
            List<StateMaster> objstate = new List<StateMaster>();
            objstate = GetStateDataFromDB();
            objstate.Insert(0, objStateMaster);
            SelectList stateList = new SelectList(objstate, "Id", "StateName");
            objstatemodel.StateList = stateList;

            /*For tehsil*/
            TehsilModel objtehsil = new TehsilModel();
            objtehsil.Id = 0;
            objtehsil.TehsilName = "Select Tehsil";
            List<TehsilModel> objtehsillisdt = new List<TehsilModel>();
            objtehsillisdt.Insert(0, objtehsil);
            SelectList tehsilList = new SelectList(objtehsillisdt, "Id", "TehsilName");
            objstatemodel.TehsilList = tehsilList;

            return View(objstatemodel);
        }
        ///


        /// This function will return all the tehsile by state id
        ///
      public ActionResult GetAllTehsilByStateID(int stateID)
        {
            List<TehsilModel> getTehsilstateID = new List<TehsilModel>();
            getTehsilstateID = GetTehsilDataFromDB().Where(m => m.StateId == stateID).ToList();
            SelectList districtList = new SelectList(getTehsilstateID, "Id""TehsilName");
            return Json(districtList);
        }
        ///


        /// This function will return data collection
        ///

        ///
        private List<TehsilModel> GetTehsilDataFromDB()
        {
            List<TehsilModel> objTehsil = new List<TehsilModel>();
            objTehsil.Add(new TehsilModel { Id = 1, StateId = 1, TehsilName = "Tehsil1" });
            objTehsil.Add(new TehsilModel { Id = 2, StateId = 1, TehsilName = "Tehsil2" });
            objTehsil.Add(new TehsilModel { Id = 3, StateId = 2, TehsilName = "Tehsil3" });
            objTehsil.Add(new TehsilModel { Id = 4, StateId = 2, TehsilName = "Tehsil4" });
            objTehsil.Add(new TehsilModel { Id = 5, StateId = 2, TehsilName = "Tehsil5" });
            return objTehsil;
        }
        ///


        /// This function will return data collection
        ///

        ///
        private List<StateMaster> GetStateDataFromDB()
        {
            List<StateMaster> objStateMaster = new List<StateMaster>();
            objStateMaster.Add(new StateMaster { Id = 1, StateName = "State1" });
            objStateMaster.Add(new StateMaster { Id = 2, StateName = "State2" });
            return objStateMaster;
        }
    }
}

       
In above code I have assigned static data in a the collection. You just use your DB data to fill the list.  In above code please check this action method “GetAllTehsilByStateID”.

        public ActionResult GetAllTehsilByStateID(int stateID)
        {
            List<TehsilModel> getTehsilstateID = new List<TehsilModel>();
            getTehsilstateID = GetTehsilDataFromDB().Where(m => m.StateId == stateID).ToList();
            SelectList districtList = new SelectList(getTehsilstateID, "Id", "TehsilName");
            return Json(districtList);
        }

In above code I a filtering the data on bases of state id and passing it as a Json.

Now generate the view and add the below code.
@model MvcApplication1.Models.StateMasterModel
@{
    ViewBag.Title = "Ajax Cascaded Dropdown List Using jQuery in Asp.net MVC and C#.Net";
}
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script language="javascript">
    function GetAllTehsil(val) {
        var urlmodel = "/Home/GetAllTehsilByStateID/"; // FOR GETTING ALL MODELCODE
        $('#ddlTehsil').html("");
        $.ajax({
            url: urlmodel,
            data: { stateID: val },
            cache: false,
            type: "POST",
            dataType: 'json',
            success: function (data) {
                var markup = "< option value='0' >Select Tehsil</ option >";
                for (var x = 0; x < data.length; x++) {
                    markup += "< option value=" + data[x].Value + ">" + data[x].Text + "</ option >";
                }
                $('#ddlTehsil').html(markup).show();
            },
            error: function (reponse) {
                $('#ddlTehsil').html("< option value='0' >Select Tehsil</ option >");
            }

        });
    }
</script>
@using (Html.BeginForm("Index", "Home"))
{
    <table width="100%" cellpadding="5" cellspacing="0" border="1">
        <tr>
            <td align="right">
                State :
            </td>
            <td align="left">@Html.DropDownList("State", (SelectList)Model.StateList, new { @style = "width:150px;", @id = "ddlstate", @onchange = "javascript:GetAllTehsil(this.value);" })
            </td>
        </tr>
        <tr>
            <td align="right">
                Tehsil :
            </td>
            <td align="left">@Html.DropDownList("Tehsil", (SelectList)Model.TehsilList, new { @style = "width:150px;", @id = "ddlTehsil" })
            </td>
        </tr>
    </table>
   
}

In above code I have used jquery ajax function. In this function I have passed the controller and action name as a url and data type is json. Defining Json type is mandatory.  Without this we will not able to retrieve data from returned value in success function.

So we have done run the application and check the output.



DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014
back to top