0

In ASP.Net MVC 4 I need to post a json data in to controller using ajax method and convert json back to model. i am able to get json from my model, but I can't convert it back. i got an exception in my controller. here I create a model object that is called by another ajax method as json type. and posting this data using another ajax method.

Here is my code:

public class LiveController : Controller
{
    //
    // GET: /Live/

    public JsonResult myproduct()
    {
        Product Book = new Product {pId=1,pName="Novel" };
        return Json(Book,JsonRequestBehavior.AllowGet);
    }

    public ActionResult viewproduct()
    {
        return View();
    }
    [HttpPost]
    public String loadproduct(String Book1)
    {

        Product values = JsonConvert.DeserializeObject<Product>(Book1);
        return "ready";
    }
}

public class Product
{
    public string pName { get; set; }
    public int pId { get; set; }
}

$(document).ready(function () {

    var Book;
    $('#searchbtn').click(function () {
        $.ajax({
            url: "/Live/myproduct",
            type: "GET",
            cache: false,
            dataType: "json",
            contentType: "application/json",
            data: {},

            success: function (result) {

                Book = result;
                $.each(result, function (key, val) {
                    $('.prolist').append("<li>" + val + "</li>");

                });
            }
        });

    });
    $('#postbtn').click(function () {

         var Book1 = JSON.stringify(Book);

        $.ajax({
            url: "/Live/loadproduct",
            type: "POST",
            cache: false,
            async: true,
            dataType: "json",
            contentType: "application/json",
            data:Book1  ,

            success: function (result) {
                alert("success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
            }
        });
    });
});

Please provide a solution.

2 Answers 2

0

do like this:

var Jsonobject = JsonConvert.DeserializeObject<Product>("jsonstring");// pass your string json here

Product result = Jsonobject.Product;
Sign up to request clarification or add additional context in comments.

5 Comments

shwo the json which is returned??
i have change the code as you said,but now i am getting this error:Unexpected character encountered while parsing value: j. Path '', line 0, position 0.
i got this json : {"pId":1,"pName":"test"}
json is not well.. see this :stackoverflow.com/questions/23240084/…
At last I got the answer , I have to made a little change in the code,Thanks to Ehsan, I will post the correct answer in tomorrow, now I have no right.
0

Here is the code that worked for me

public class LiveController : Controller { // // GET: /Live/

    public JsonResult myproduct()
    {
        Product Book = new Product {pId=1,pName="Novel" };
        return Json(Book,JsonRequestBehavior.AllowGet);
    }

    public ActionResult viewproduct()
    {
        return View();
    }
    [HttpPost]
    public JsonResult loadproduct()
    {
        var request = ControllerContext.HttpContext.Request;



        request.InputStream.Seek(0, SeekOrigin.Begin);
        var json= new StreamReader(request.InputStream).ReadToEnd(); ;




        Product result = JsonConvert.DeserializeObject<Product>(json);// pass your string json here

        return Json(result,JsonRequestBehavior.AllowGet);

        //var Jsonobject = JsonConvert.DeserializeObject<Product>("jsonstring"); 
        //Product result = Jsonobject;
        //return "ready";
    }
}

}

$(document).ready(function () {

    var Book;
    $('#searchbtn').click(function () {
        $.ajax({
            url: "/Live/myproduct",
            type: "GET",
            cache: false,
            dataType: "json",
            contentType: "application/json",
            data: {},

            success: function (result) {

                Book = result;
                $.each(result, function (key, val) {
                    $('.prolist').append("<li>" + val + "</li>");

                });
            }
        });

    });
    $('#postbtn').click(function () {


        var jsonstring = JSON.stringify(Book);

        $.ajax({
            url: "/Live/loadproduct",
            type: "POST",
            cache: false,
            async: true,
            dataType: "text",
            contentType: "application/json",
            data: jsonstring,

            success: function (result) {
                console.log(result);
                alert(result)
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
            }
        });
    });













});

Comments

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.