1

Since two weeks, I'm trying to Create a ASP.NET MVC 4 Application which is contain 3 drop down lists. Those are Country, State and City . I'm Following this article

These database list details I call from databas

Connection string :

<connectionStrings>
    <add name="CACD_Con" connectionString="metadata=res://*/Models.Project_Name.csdl|res://*/Models.Project_Name.ssdl|res://*/Models.Project_Name.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.0.000;initial catalog=CACD;persist security info=True;user id=000;password=000000000;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

controller class:

 public class CacadingController : Controller
{
    private ProjectContext db = new ProjectContext();

    public ActionResult Index()
    {
        ViewBag.CountryId = new SelectList(db.Countrys, "CountryId", "CountryName");
        return View();
    }

    public JsonResult StateList(int Id)
    {
        var state = from s in db.States
                       where s.CountryId == Id
                       select s;
        return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
    }

    public JsonResult Citylist(int id)
    {
        var city = from c in db.Citys
                   where c.StateId == id
                   select c;
        return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
    }

    public IList<State> Getstate(int CountryId)
    {
        return db.States.Where(m => m.CountryId == CountryId).ToList();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult LoadClassesByCountryId(string CountryName)
    {
        var stateList = this.Getstate(Convert.ToInt32(CountryName));
        var stateData = stateList.Select(m => new SelectListItem()
        {
            Text = m.StateName,
            Value = m.CountryId.ToString(),
        });
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

}

Model Class :

public partial class ProjectContext : DbContext
    {
        public ProjectContext()
            : base("CACD")
        {
        }

        public DbSet<Country> Countrys { get; set; }
        public DbSet<State> States { get; set; }
        public DbSet<City> Citys { get; set; }

        }

    public class Country
    {
        [Key]
        public int CountryId { get; set; }
        public string CountryName { get; set; }

        public virtual ICollection<State> States { get; set; }
    }


    public class State
    {
        [Key]
        public int StateId { get; set; }
        public string StateName { get; set; }
        [ForeignKey("Country")]
        public int CountryId { get; set; }

        public virtual Country Country { get; set; }
        public virtual ICollection<City> Citys { get; set; }
    }

    public class City
    {
        [Key]
        public int CityId { get; set; }
        public string CityName { get; set; }
        [ForeignKey("State")]
        public int StateId { get; set; }

        public virtual State State { get; set; }
    }

View File(cshtml)

@model Project_Name.Models.ProjectContext

@using (Html.BeginForm())
{
@Html.DropDownList("Country", ViewBag.CountryId as SelectList, "Select a Country", new { id="Country" })<br />
    <select id="State" name="state"></select><br />
    <select id="city" name="City"></select><br />
}

@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(function () {
        $('#Country').change(function () {
            $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) {
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) {
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $('#State').html(items);
            });
        });

        $('#State').change(function () {
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
                var items = '<option>Select a City</option>';
                $.each(data, function (i, city) {
                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                });
                $('#city').html(items);
            });
        });
    });
</script>

But drop down's not showing any of data in database , Really appreciate if you can show me the correct path

4
  • Whats not working? Is the first dropdown (Countries) being populated? Commented Jan 12, 2015 at 2:28
  • not any of above dropdwon doesn't populate anything Commented Jan 12, 2015 at 4:53
  • Then you need to debug your code - does db.Countrys return any valid data? (and you don't need @model AFFEMS2_HEC.Models.ProjectContext in the view - that not your model!) Commented Jan 12, 2015 at 5:34
  • its compile well without any error , but db.Countrys doesn't return any data Commented Jan 12, 2015 at 6:59

3 Answers 3

1
   where  cityList is list containing city model

var result = from item in cityList
                                 select new
                                 {
                                     value = item.CityId,
                                     text = item.Name
                                 };
                    return Json(result, JsonRequestBehavior.AllowGet);

and in script add
 $('#State').change(function () {
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
                 var items = [];
                items.push("<option>Select City</option>");
                $.each(data, function () {
                    items.push("<option value=" + this.value + ">" + this.text + "</option>");
                });
                $(city).html(items.join(' '));
            });
        });

do same for state
Sign up to request clarification or add additional context in comments.

Comments

1

I used the first on my project but doesnt save the info on database .. to save Country I did on the view this:

 @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryId as SelectList, "Select a Country", new { id = "Country", @class = "form-control" })<br />

but the next doesnt save but if I change it like above the script doesn't work
Any help...

**<select id="StateId" name="state" class="form-control"></select><br />
<select id="CityId" name="City" class="form-control"></select><br />**

The Script **

@section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/jscript">
        $(function () {
            $('#Country').change(function () {
                $.getJSON('/AddressBooks/StateList/' + $('#Country').val(), function (data) {
                    var items = '<option>Select a State</option>';
                    $.each(data, function (i, state) {
                        items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                    });
                    $('#StateId').html(items);
                    $('#CityId').html(null);
                });
            });

            $('#StateId').change(function () {
                $.getJSON('/AddressBooks/Citylist/' + $('#StateId').val(), function (data) {
                    var items = '<option>Select a City</option>';
                    $.each(data, function (i, city) {
                        items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                    });
                    $('#CityId').html(items);
                });
            });
        });
        </script>

**

On the controller

public ActionResult Create()
        {

            ViewBag.CustomerId = new SelectList(db.Customers, "Id", "FullName");
            ViewBag.CountryId= new SelectList(db.Countries, "CountryId", "CountryName");
            return View();
        }
        public JsonResult StateList(int Id)
        {
            var state = from s in db.States
                        where s.CountryId == Id
                        select s;

            return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Citylist(int id)
        {
            var city = from c in db.Cities
                       where c.StateId == id
                       select c;

            return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
        }

        public IList<State> Getstate(int CountryId)
        {
            return db.States.Where(m => m.CountryId == CountryId).ToList();
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByCountryId(string CountryName)
        {
            var stateList = this.Getstate(Convert.ToInt32(CountryName));
            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = m.CountryId.ToString(),
            });
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }

Comments

0

I solved the problem

@Html.DropDownList("CountryId", null, htmlAttributes: new { id = "Country", @class = "form-control" })

@Html.DropDownListFor(model => model.StateId, new SelectList(Enumerable.Empty<selectlistitem>(), "StateId", "StateName"), "Select State", new { id = "StateId", @class = "form-control" })

@Html.DropDownListFor(model => model.CityId, new SelectList(Enumerable.Empty<selectlistitem>(), "CityId", "CityName"),"Select city",new { id = "CityId", @class = "form-control" })

Json

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#Country').change(function () {
$('#StateId').html(null)
$('#CityId').html(null);
$.getJSON('/AddressBooks/StateList/' + $('#Country').val(), function (data)        {
$.each(data, function (i, state) {
$("#StateId").append(
"<option value="" + state.Value + "">" + state.Text + "</option>")
});
});
});

$('#StateId').change(function () {
$('#CityId').html(null);
$.getJSON('/AddressBooks/Citylist/' + $('#StateId').val(), function (data) {
$.each(data, function (i, city) {
$("#CityId").append(
"<option value="" + city.Value + "">" + city.Text + "</option>");

});
});
});
});
</script>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.