MVC $ .getJSON for cascading drop-down list
source link: https://www.codesd.com/item/mvc-getjson-for-cascading-drop-down-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
MVC $ .getJSON for cascading drop-down list
I have a cascading dropdown list that is not working. I'm not sure what I am missing here because I see the data being returned in the controller but it is not getting loaded into the child dropdown list control. It appears that the data is not being received by the getJSON call.
Controller code:
public ActionResult GetCampaignsForPartner(int partnerKey)
{
PartnershipsService svc = new PartnershipsService();
var oCampaigns = svc.Client.GetCampaigns();
var oReturn =
(from c in oCampaigns
where c.PartnerKey == partnerKey
select new SelectListItem
{
Text = c.CampaignName,
Value = c.CampaignKey.ToString()
}).ToList();
return Json(new SelectList(oReturn, "CampaignName", "CampaignKey"), JsonRequestBehavior.AllowGet);
}
Script is:
$(document).ready(function () {
$("#ddlPartners").change(function () {
var value = $("#ddlPartners option:selected").val();
$('#ddlCampaigns').empty();
$.getJSON('@Url.Action("GetCampaignsForPartner")', { partnerKey: value }, function (list) {
console.log(list);
$.each(list, function (key, value) {
var el = $('<option></option>')
.attr('value', key)
.html(value);
$('#ddlCampaigns').append(el);
});
});
});
});
HTML is:
<div>
@Html.LabelFor( x => x.PartnerKey, "Partner:", lbl_class ) @Html.DropDownListFor(x => x.PartnerKey, Model.Partners, new { @id = "ddlPartners", @class = "editor-field" } ) @Html.ValidationMessageFor( x => x.PartnerKey )
</div>
<div>
@Html.LabelFor( x => x.CampaignKey, "Campaign:", lbl_class ) @Html.DropDownListFor(x => x.CampaignKey, Model.Campaigns, new { @id = "ddlCampaigns", @class = "editor-field" } ) @Html.ValidationMessageFor( x => x.CampaignKey )
</div>
Any help with getting this working would be greatly appreciated. Thanks!
You can try to use JsonResult instead of ActionResult, I think it makes more sense too.
public JsonResult GetCampaignsForPartner(int partnerKey)
{
PartnershipsService svc = new PartnershipsService();
var oCampaigns = svc.Client.GetCampaigns();
var oReturn =
(from c in oCampaigns
where c.PartnerKey == partnerKey
select new SelectListItem
{
Text = c.CampaignName,
Value = c.CampaignKey.ToString()
}).ToList();
return new JsonResult() { Data = new SelectList(oReturn, "CampaignName", "CampaignKey"), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
You can see if it return some value first by calling it from the browser:
http://web/controller/GetCAmpaignsForPartner?partnerKey=1
If you see some data there, then your controller is working good and you should check the JS code, but it looks good too.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK