I am trying to update a checkbox list by using jquery to listen for a change. For some reason it seems that the controller method is not returning the JSON. I based this code on this example.
In the example the controller calls return Json(data, JsonRequestBehavior.AllowGet);
, but I could only get return Json(data)
working. My theory is that the return type has to specifically allow GET, but I dont know how to get that working.
My code works fine, with no errors and all 3 console statements appear in the web browser.
my jquery code (in my view):
$('#lgcheese').change(function() {
ddToPopulate.empty();
console.log('change detected');
$.getJSON(CoIdUrl, { CoName: $(this).val() }, function (data) {
console.log('in shit');
if (!data) { console.log('no json returned');return;}
ddToPopulate.append($('<ListItem></ListItem>').val('').text('Please select'));
$.each(data, function(index, item) {
ddToPopulate.append($('<ListItem></ListItem>').val(item.Value).text(item.Text));
});
});
});
later in my view I call: <CheckBoxList ID="cheesebox"></CheckBoxList>
to create the checkbox list the jquery is supposed to populate.
My controller has method:
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
[HttpGet]
public JsonResult FetchCoIds(string CoName)
{
var data = new { Value = "val", Text = CoName+"_val1" };
return Json(data);
}
You need to update your action method with behavior. Try this
[HttpGet]
public JsonResult FetchCoIds(string CoName)
{
var data = new { Value = "val", Text = CoName+"_val1" };
return Json(data, JsonRequestBehavior.AllowGet);
}
Note:this answer is applicable for asp.net MVC not for Core