【问题标题】:controller not returning json result to view控制器不返回 json 结果以查看
【发布时间】: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));
        });
    });
});

稍后在我看来,我调用:&lt;CheckBoxList ID="cheesebox"&gt;&lt;/CheckBoxList&gt; 来创建 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


【解决方案1】:

您需要使用行为更新您的操作方法。试试这个

   [HttpGet]
    public JsonResult FetchCoIds(string CoName)
    {
        var data = new { Value = "val", Text = CoName+"_val1" };
        return Json(data, JsonRequestBehavior.AllowGet);
    }

注意:此答案适用于 asp.net MVC,不适用于 Core

【讨论】:

  • JsonRequestBehavior 在我当前的上下文中不存在
  • 感谢您的帮助,我试过但不幸得到:JsonResult does not contain a constructor that takes 0 arguments
  • 告诉我你正在使用的 JsonResult 的完整类名
  • json类来自:using Microsoft.AspNetCore.Mvc;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多