I want to fill city dropdown automatically from database according to state dropdown in ASP.NET MVC and Ajax

StackOverflow https://stackoverflow.com/questions/22295191

  •  12-06-2023
  •  | 
  •  

Question

I want to get city list from database and store selected city's id into database. I have used Ajax to call function of member class. But it is not working, please help me to sort this out.

Here is my Model:

    [Required]
    [Display(Name = "State")]
    public int stateid { get; set; }
    public string stateName { get; set; }
    public List<SelectListItem> stateList = new List<SelectListItem>();
    [Required]
    [Display(Name = "City")]
    public int Cityid { get; set; }
    public string CityName { get; set; }
    public List<SelectListItem> CityList = new List<SelectListItem>();

    clubDataContext cd = new clubDataContext();
    public void insertmember(M_Reg m)
    {
        M_Registarion m1 = new M_Registarion();
        m1.M_StatteId = m.stateid;
        m1.M_CityId = 1; //temporary storing 1
        cd.M_Registarions.InsertOnSubmit(m1);
        cd.SubmitChanges();
    }

Here is my controller:

    [HttpGet]
    public ActionResult Registration()
    {
        var model = new M_Reg();
        using (var db = new clubDataContext())
        {
         model.stateList = content2.Select(c2 => new SelectListItem
            {
                Text = c2.S_Name,
                Value = c2.S_ID.ToString()
            }).ToList();
        }
        return View(model);

    }
     [HttpGet]
      public SelectList getCity(int stateId, int selectCityId)
      {
        var db = new clubDataContext();
        var model = new M_Reg();
        var content = from p in db.CityInfos where p.S_ID == stateId
                      select new { p.C_ID, p.C_Name };
        model.CityList = content.Select(c => new SelectListItem
        {
            Text = c.C_Name,
            Value = c.C_ID.ToString()
        }).ToList();
        return new SelectList(model.CityList, "Value", "Text", selectCityId);

    }

View: Razor code:

         <div class="editor-label">
        @Html.LabelFor(m=> m.stateid)
        </div>
         <div class="editor-field">
            @Html.DropDownListFor(m => m.stateid,Model.stateList)
            @Html.ValidationMessageFor(m => m.stateid)
        </div>
        <div class="editor-label">
        @Html.LabelFor(m=> m.Cityid)
        </div>
         <div class="editor-field">
            @Html.DropDownListFor(m => m.Cityid, Model.CityList)
            @Html.ValidationMessageFor(m => m.Cityid, Model.c)
        </div>

Ajax code:

    $("#stateid").change(function () {
         $.ajax({
             type: "POST",
             url: '@Url.Action("Member", "getCity")',
             data: { stateId: $("#stateid > option:selected").attr("value") },
             success: function (data) {
                 var items = [];
                 items.push("<option>--Choose Your City--</option>");
                 $.each(data, function () {
                     items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
                 });
                 $("#Cityid").html(items.join(' '));
             }
         })
     });
Was it helpful?

Solution 2

Finally, this code works...

Model Class:

clubDataContext _db = new clubDataContext();
    [Required]
    [Display(Name="City")]
    public virtual string icityid { get; set; }
    public List<SelectListItem> cityList = new List<SelectListItem>();
    [Required]
    [Display(Name = "State")]
    public virtual string istateid { get; set; }
    public SelectList getState()
    {
        IEnumerable<SelectListItem> stateList = (from m in _db.StateInfos select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.S_Name, Value = m.S_ID.ToString() });
        return new SelectList(stateList, "Value", "Text", istateid);
    }

View :

<div class="editor-label">
        @Html.LabelFor(m=> m.istateid)
        </div>
         <div class="editor-field">
            @Html.DropDownListFor(m => m.istateid,Model.getState(),"--Choose your State--")
            @Html.ValidationMessageFor(m => m.istateid)
        </div>
        <div class="editor-label">
        @Html.LabelFor(m=> m.icityid)
        </div>
         <div class="editor-field">
            @Html.DropDownListFor(m => m.icityid,Model.cityList,"--Choose your City--")
            @Html.ValidationMessageFor(m => m.icityid)
        </div>

Ajax:

$('#istateid').change(function(){
     $.ajax({
     type:"POST",
     url:'@Url.Action("getCityJson","Member")',
     data: { stateId : $("#istateid > option:selected").attr("value")},
     success: function (data){
     var items= [];
     $.each(data,function(){
        items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
        });
        $("#icityid").html(items.join(' '));
        }
       })
     });

And Controller:

[HttpPost]
    public JsonResult getCityJson(string stateId, string selectCityId=null)
    {
        return Json(getCity(stateId, selectCityId));
    }
    public SelectList getCity(string stateId, string selectCityId = null)
    {
        var db = new clubDataContext();
        IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
        if (!string.IsNullOrEmpty(stateId))
        {
            int _stateId = Convert.ToInt32(stateId);
            cityList = (from m in db.CityInfos where m.S_ID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.C_Name, Value = m.C_ID.ToString() });
        }
        return new SelectList(cityList, "Value", "Text", selectCityId);
    }

OTHER TIPS

Try Like This

Here Controller :

   public JsonResult functionname(){
   List<string> City = new List<string>();
   var DBcity = yourDBentity.TableName.Where(x=>x.columnname==condition).select(x=>x.city);
   foreach(var i in DBcity){
      City.Add(i);
    }
   return Json(City, JsonRequestBehavior.AllowGet);
   }

Jquery:

$(document).ready(function (result) {
  $.post('/yourcontorller/functionname', {parameter : parameter }, function (result) {
    $.each(result, function (key, value) {
            $('#yourDropdownId').append($("<option></option>").html(value).val(value));
        });
  },"json");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top