Reputation: 543
This seems so simple but has really stumped me..basically I am trying to assign valid JSON being returned from an MVC 4 action (allows the inserting of a user) via an AJAX call. The JSON is being returned successfully but I cannot parse the JSON on the client side so that I can assign the variables to local storage. If someone could please show me where I am going wrong I would be very grateful as I have been stuck on this for one whole day, thanks.
JSON
{ "Success": true, "user": { "UserId": 7, "Name": "Bob", "Email": "[email protected]", "Occupation": "Dev", "Country": "UK", "RegistrationNumber": "B001", "UserDate": "/Date(1401840000000)/", "Results": null } }
MVC 4 Action
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
repository.InsertUser(user);
repository.Save();
if (Request.IsAjaxRequest())
{
//success
return Json(new { Success = true, user });
// no success
return Json(new { Success = false, Message = "Error" });
}
return RedirectToAction("Index");
}
return View(user);
}
AJAX //Register self.create = function () {
if (User.Name() != "" && User.Email() != "" && User.Occupation() != "") {
$.ajax({
url: '/User/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
if (data.Success) {
//NOTE the following not working
var dataToStore = JSON.stringify(data);
localStorage.setItem("UserId", dataToStore.UserId);
//NOTE the following alert outputs an undefined message?
alert(JSON.parse(localStorage.getItem("UserId")))
//NOTE the following not being assigned either?
localStorage.setItem("Name", data.Name);
localStorage.setItem("Email", data.Email);
localStorage.setItem("Occupation", data.Occupation);
localStorage.setItem("Country", data.Country);
localStorage.setItem("RegistrationNumber", data.RegistrationNumber);
//testing output
viewModel.UserId(data.UserId);
//redirect to questions
// window.location = "QnA.html"
}
else {
viewModel.UserId("Error user not created, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter all fields');
}
};
Upvotes: 1
Views: 733
Reputation: 3228
When accessing user data you have to access like follows;
data.user.Name
data.user.Email
And set the Json request behavior when you return JSON as follows;
return Json(new { Success = true, user } , JsonRequestBehavior.AllowGet });
Thanks!
Upvotes: 1
Reputation:
Firstly when u r returning json result update it as follow
return Json(new { Success = true, user } , JsonRequestBehavior.AllowGet });
return Json(new { Success = false, Message = "Error" } , JsonRequestBehavior.AllowGet});
Upvotes: 1