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.