Create Cascading (Dependent) DropDownList with Partial View using jQuery AJAX in ASP.Net MVC

Last Reply one year ago By dharmendr

Posted one year ago

in mvc i m adding partial view using ajax,but that partila view contains footer of view, means now there are 2 footer.how we can hide footer of partial view.

var cntry = db.Country_Name.ToList();
List<SelectListItem> countre = new List<SelectListItem>();
foreach (Country_Name item in cntry)
{
    countre.Add(new SelectListItem
    {
        Text = item.Country,
        Value = item.Country_Id.ToString()
    });
}
ViewBag.country = countre;

 

<div class="form-group">
    @Html.LabelFor(model => model.First_Name, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.First_Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.First_Name, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, new { @class = "form-control col-md-3", @id = "ddrcountry", onchange = "javascript:return getstates()" })
        @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
    </div>
</div>

<div id="partialStateView">

</div>
<div class="col-md-5">
    @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="SignUp" onclick="javascript: return checkdate()" class="btn btn-default" />
    </div>
</div>


@section Scripts{
    <script>
        function getstates() {

            var drpvalue = document.getElementById("ddrcountry").value;
            // alert(drpvalue);
            if (drpvalue == 0) {

                return false;
            }

            $.ajax({
                url: '@Url.Action("GetStates", "Home")',
                dataType: "html",
                data: { "sb": drpvalue },
                type: "GET",
                contentType: "application/json",
                success: function (response) {

                    $('#partialStateView').html(response);
                },
                error: function (err) {
                    alert(err.responseText);
                }
            });
        }
    </script>
}

 

public ActionResult GetStates(int sb)
{
    var states = db.State_Name.Where(s => s.Country_Id == sb).ToList();

    List<SelectListItem> statelst = new List<SelectListItem>();
    foreach (State_Name item in states)
    {
        statelst.Add(new SelectListItem
        {
            Text = item.State,
            Value = item.State_Id.ToString()

        });
    }
    ViewBag.Statelist = statelst;
    return View();
}

 

<div class="row col-md-6">

    <div class="form-group col-md-12">
        @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.State, (IEnumerable<SelectListItem>)ViewBag.Statelist, "Select State", new { @class = "form-control col-md-3", @id = "ddrstate", onchange = "javascript:return getcity()" })
            @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
        </div>
    </div>

    <div id="partialCityView" class="col-md-12">

    </div>
</div>

@section Scripts{
    <script>
        /////Get states according to Country
        function getcity() {
            alert("ok");
            var drpvalue = document.getElementById("ddrstate").value;
            // alert(drpvalue);
            if (drpvalue == 0) {

                return false;
            }

            $.ajax({
                url: '@Url.Action("GetCity", "Home")',
                dataType: "html",
                data: { "sb": drpvalue },
                type: "GET",
                contentType: "application/json",
                success: function (response) {

                    $('#partialCityView').html(response);
                },
                error: function (err) {
                    alert(err.responseText);
                }
            });
        }
    </script>
}

 

public ActionResult GetCity(int sb)
{
    var cities = db.City_Name.Where(s => s.State_Id == sb).ToList();

    List<SelectListItem> citylst = new List<SelectListItem>();
    foreach (City_Name item in cities)
    {
        citylst.Add(new SelectListItem
        {
            Text = item.City,
            Value = item.City_Id.ToString()

        });
    }
    ViewBag.Citylist = citylst;
    return View();
}

 

@{
    Layout = null;
}
<div class="form-group col-md-6">
    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.City, (IEnumerable<SelectListItem>)ViewBag.Citylist, "Select City", new { @class = "form-control col-md-3", @id = "ddrcity" })
        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
    </div>
</div>

 

[HttpPost]
public ActionResult SignUp(FormCollection form)
{
    User usr = new User();
    usr.Name = form["First_Name"].ToString();
    usr.Country = Convert.ToInt32(form["Country"].ToString());
    usr.State = Convert.ToInt32(form["State"].ToString());
    usr.City = Convert.ToInt32(form["City"].ToString());
}

Problem in design and on HttpPost not able to find value of selected state and city

You are viewing reply posted by: dharmendr one year ago.
Posted one year ago

Hi mukesh1,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used three tables Countries, States and Cities.

You can download the database table SQL by clicking the download link below.

Download SQL file

Controller

public class HomeController : Controller
{
    CascadingEntities db = new CascadingEntities();
    public ActionResult Index()
    {
        var countries = db.Countries.ToList();
        List<SelectListItem> countryList = new List<SelectListItem>();
        foreach (Country country in countries)
        {
            countryList.Add(new SelectListItem
            {
                Text = country.CountryName,
                Value = country.CountryId.ToString()
            });
        }
        ViewBag.Country = countryList;
        return View();
    }

    [HttpGet]
    public ActionResult GetStates(int countryId)
    {
        var states = db.States.Where(s => s.CountryId == countryId).ToList();
        List<SelectListItem> stateList = new List<SelectListItem>();
        foreach (State state in states)
        {
            stateList.Add(new SelectListItem
            {
                Text = state.StateName,
                Value = state.StateId.ToString()
            });
        }
        ViewBag.State = stateList;
        return View("_State");
    }

    [HttpGet]
    public ActionResult GetCities(int stateId)
    {
        var cities = db.Cities.Where(s => s.StateId == stateId).ToList();
        List<SelectListItem> cityList = new List<SelectListItem>();
        foreach (City city in cities)
        {
            cityList.Add(new SelectListItem
            {
                Text = city.CityName,
                Value = city.CityId.ToString()

            });
        }
        ViewBag.City = cityList;
        return View("_City");
    }

    [HttpPost]
    public ActionResult SignUp(FormCollection form)
    {
        int Country = Convert.ToInt32(form["CountryName"].ToString());
        int State = Convert.ToInt32(form["StateName"].ToString());
        int City = Convert.ToInt32(form["CityName"].ToString());
        TempData["Message"] = "Country: " + Country;
        TempData["Message"] += "\\nState: " + State;
        TempData["Message"] += "\\nCity: " + City;
        return RedirectToAction("Index");
    }
}

View

Index View

@model _570014_Cascading_DropDown_PartialView.Country

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
    <div>
        @using (Html.BeginForm("SignUp", "Home", FormMethod.Post))
        {
            <div class="form-group">
                @Html.LabelFor(model => model.CountryName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.CountryName, (IEnumerable<SelectListItem>)ViewBag.Country, new { @class = "form-control col-md-3", @id = "ddlCountries", onchange = "return GetStates()" })
                </div>
            </div>
            <div id="partialStateView">
            </div>
            <input type="submit" name="Save" value="Save" class="btn btn-primary form-group" />
        }
    </div>
    <script type="text/javascript">
        function GetStates() {
            var country = document.getElementById("ddlCountries").value;
            if (country == 0) {
                return false;
            }
            $.ajax({
                url: '@Url.Action("GetStates", "Home")',
                dataType: "html",
                data: { "countryId": country },
                type: "GET",
                contentType: "application/json",
                success: function (response) {
                    $('#partialStateView').html(response);
                },
                error: function (err) {
                    alert(err.responseText);
                }
            });
        }
    </script>
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("@TempData["Message"]");
            });
        </script>
    }
</body>
</html>

State Partial View

@model _570014_Cascading_DropDown_PartialView.State

@{
    Layout = null;
}

<div class="row col-md-6">
    <div class="form-group col-md-12">
        @Html.LabelFor(model => model.StateName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.StateName, (IEnumerable<SelectListItem>)ViewBag.State, "Select State", new { @class = "form-control col-md-3", @id = "ddlStates", onchange = "return GetCities()" })
        </div>
    </div>

    <div id="partialCityView" class="col-md-12">
    </div>
</div>
<script type="text/javascript">
    function GetCities() {
        var state = document.getElementById("ddlStates").value;
        if (state == 0) {
            return false;
        }
        $.ajax({
            url: '@Url.Action("GetCities", "Home")',
            dataType: "html",
            data: { "stateId": state },
            type: "GET",
            contentType: "application/json",
            success: function (response) {
                $('#partialCityView').html(response);
            },
            error: function (err) {
                alert(err.responseText);
            }
        });
    }
</script>

City Partial View

@model _570014_Cascading_DropDown_PartialView.City

@{
    Layout = null;
}

<div class="form-group col-md-6">
    @Html.LabelFor(model => model.CityName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.CityName, (IEnumerable<SelectListItem>)ViewBag.City, "Select City", new { @class = "form-control col-md-3", @id = "ddlCities" })
    </div>
</div>

Screenshot