JSON发送的数据始终为null

时间:2015-05-26 09:41:06

标签: javascript ajax json asp.net-mvc

第一个问题

我使用另一个程序员的代码。

我必须正确检查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是llways null。为什么?真的,我不知道我哪里出错了。

第二部分

在控制器中我返回JSON - 它的好主意?如何在Ajax中从这个控制器获得响应

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

或JsonResult isValid(dynamic dataFromJson)

相关问题