I want to fill city dropdown automatically from database according to state dropdown in ASP.NET MVC and Ajax -
i want city list database , store selected city's id database. have used ajax call function of member class. not working, please me sort out.
here 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 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 = p in db.cityinfos 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 city--</option>"); $.each(data, function () { items.push("<option value=" + this.value + ">" + this.text + "</option>"); }); $("#cityid").html(items.join(' ')); } }) });
try 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 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"); });
Comments
Post a Comment