Sebastian
Sebastian

Reputation: 15

data send by JSON are always null

First problem

I work with code for another coder.

I must check correctly cron expression and I can change many line code in program. I take argument from form and trying send this data to controller MVC

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

and

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);
}

Controller in MVC looks like:

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);
    }
 }

The parameters dataFromJson are llways null. Why? Really, I don't see where I went wrong.

Second part

In controller I return JSON - its good idea? How to get response from this controller in Ajax

Upvotes: 1

Views: 80

Answers (2)

jereesh thomas
jereesh thomas

Reputation: 163

Change the paramter type of the Controller action method to JObject (Newtonsoft.Json.Linq)or dynamic public JsonResult isValid(JObject dataFromJson)

or JsonResult isValid(dynamic dataFromJson)

Upvotes: 0

Madhu
Madhu

Reputation: 2551

Change the ajax data as follows.

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);
}

In the above, i changed var tmp = JSON.stringify({dataFromJson : checkExpression}); this, now it can be bound at the server side. And also change the dataType as json if you are expecting a json from server response.

Regarding the second part, its based on your requirement, you can either use Content or Json as per your need.

Upvotes: 1

Related Questions