【发布时间】:2018-04-05 14:52:16
【问题描述】:
我正在尝试使用 jquery 来更新复选框列表以侦听更改。由于某种原因,控制器方法似乎没有返回 JSON。我将此代码基于this example。
在示例中,控制器调用return Json(data, JsonRequestBehavior.AllowGet);,但我只能让return Json(data) 工作。我的理论是返回类型必须专门允许 GET,但我不知道如何让它工作。
我的代码运行良好,没有错误,所有 3 个控制台语句都显示在 Web 浏览器中。
我的 jquery 代码(在我看来):
$('#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));
});
});
});
稍后在我看来,我调用:<CheckBoxList ID="cheesebox"></CheckBoxList> 来创建 jquery 应该填充的复选框列表。
我的控制器有方法:
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);
}
【问题讨论】:
-
您需要添加
JsonRequestBehavior.AllowGet。使用 GET 请求时,如果没有它,我看不出它会如何工作......? -
@RoryMcCrossan 我无法补充,因为我的 using 语句是错误的(我认为),但我无法找出正确的语句
-
我通常只使用
IActionResult,然后只使用return new { .... }。它将以 JSON 格式返回。
标签: c# jquery asp.net-core-mvc jsonresult