【问题标题】:data send by JSON are always nullJSON 发送的数据始终为空
【发布时间】:2015-06-10 17:23:22
【问题描述】:

第一个问题

我为其他编码员处理代码。

我必须正确检查 cron 表达式,并且我可以更改程序中的许多行代码。我从表单中获取参数并尝试将此数据发送到控制器 MVC

var outl = document.getElementById('Frequency').value;
var tmp = checkValid(outl);

function checkValid(checkExpression)
{
    var tmp = JSON.stringify(checkExpression);
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: String,
        type: 'POST',
        url: '/Service/isValid',
        data: tmp,
        success: function (isvalid)
        {
            return isvalid;
        }
    });
    console.log(tmp);
}

MVC 中的控制器如下所示:

public JsonResult isValid(string dataFromJson)
{
    Options options = new Options()
    {
        ThrowExceptionOnParseError = true,
        Use24HourTimeFormat = true,
    };

    try
    {
        ExpressionDescriptor ceh = new ExpressionDescriptor(dataFromJson, options);
        string description = ceh.GetDescription(DescriptionTypeEnum.FULL);
        return Json(true);
    }
    catch (FormatException)
    {
         return Json(false);
    }
 }

参数dataFromJson 始终为空。为什么?真的,我看不出哪里出错了。

第二部分

在控制器中我返回 JSON - 这是个好主意吗?如何在 Ajax 中从该控制器获取响应

【问题讨论】:

  • 感谢您在编辑方面的帮助

标签: javascript ajax json asp.net-mvc


【解决方案1】:

如下更改ajax数据。

function checkValid(checkExpression)
{
var tmp = JSON.stringify({dataFromJson : checkExpression});
$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: "json",
    type: 'POST',
    url: '/Service/isValid',
    data: tmp,
    success: function (isvalid)
    {
        return isvalid;
    }
    });
   console.log(tmp);
}

上面我改了var tmp = JSON.stringify({dataFromJson : checkExpression});这个,现在可以在服务器端绑定了。如果您期望来自服务器响应的 json,还将 dataType 更改为 json

关于第二部分,根据您的要求,您可以根据需要使用ContentJson

【讨论】:

    【解决方案2】:

    将Controller动作方法的参数类型改为JObject(Newtonsoft.Json.Linq)或动态 public JsonResult isValid(JObject dataFromJson)

    或JsonResult isValid(动态dataFromJson)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2015-09-10
      • 2018-03-03
      • 2011-08-28
      • 2014-02-10
      相关资源
      最近更新 更多