1

Here is the Javascript code

$("#JSONPost").click(function (e) {
    var jsonData = { name: "ramesh", mobile: "9xxxxxxxxx" };
    $.post(
        "/Trace/JSONPostMethod",
        jsonData,
        function (data, status) {
            alert(status);
        });
    });
});

public ActionResult JSONPostMethod(object data)
{

}

data is coming as {} instead of the { name: "ramesh", mobile: "9xxxxxxxxx" }

Any idea how to get this JSON? I don't want to create a model class to get the data.

2 Answers 2

1

Found the solution. Inside the controller method do this,

var resolveRequest = HttpContext.Request;
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
Sign up to request clarification or add additional context in comments.

Comments

0

You can modify your Json code and write something which is not confusing as below:

$("#JSONPost").click(function (e) {
    var jsonData= {};
    jsonData.Name = "Ramesh";
    jsonData.Mobile = "9xxxxxxxxx";
    
    $.ajax(
        url: "/Trace/JSONPostMethod",
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        type: 'POST',
        success: function (data, status) {
            alert(status);
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Correction in your Controller:

[HttpPost]
public JsonResult JSONPostMethod(object data)
{
   // your logic here
   return Json(data, JsonRequestBehavior.AllowGet);
}

Hope this helps.

9 Comments

No change in output,
[HttpPost] public ActionResult JSONPostMethod(object data) { string jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject(data); }
jsonStr is coming as "{}"
IN the $.ajax method, I forgot to mention the success property. I have edited my answer. Have a look. Also, the return type of your Controller should be JsonResult
If you are passing Json into a controller, it should be of Json type. I have updated my answer I am sure you will get it in your controller variable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.