Reputation: 5002
I want to retrieve JSOn data from controller and set it for window.location
.
in jquery :
$('.starcontainer').rating(function (vote, event) {
var el = $(event.target);
post = el.parent().parent().attr("data-post");
$(".loading").show();
// we have vote and event variables now, lets send vote to server.
var data = JSON.stringify({
rate: vote, id: post
});
$.ajax({
url: "/blog/rate",
dataType: "Json",
data: data,
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (responseData) {
alert(responseData);
window.location = responseData.redirect;
}
});
});
and in Controller:
[AllowAnonymous]
[HttpPost]
public JsonResult Rate(int id, int rate)
{
if (Request.IsAuthenticated)
{
try
{
var user = _db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);
PostScore score = new PostScore();
score.BlogPostId = id;
score.Score = rate;
score.UserId = user.UserId;
_db.PostScores.Add(score);
_db.SaveChanges();
}
catch (System.Exception ex)
{
// get last error
if (ex.InnerException != null)
while (ex.InnerException != null)
ex = ex.InnerException;
}
}
else
return Json(new { redirect = Url.Action("Login", "Account") }, JsonRequestBehavior.AllowGet);
return Json(new { redirect = Url.Action("Index") }, JsonRequestBehavior.AllowGet);
}
When i run it, retrieve json data {"redirect":"/Account/Login"}
for jquery. and redirect to http://localhost:2478/undefined
(return undefined for redirect).
if i return Json(Url.Action("Login", "Account") , JsonRequestBehavior.AllowGet);
it redirect to http://localhost:2478/%22/Account/Login%22
How to retrieve a url data from controller?
Upvotes: 0
Views: 1222
Reputation: 62488
According to firebug console you are getting response as string so parse it to json as it is returned as string:
"{"redirect":"/Account/Login"}"
success: function (response) {
var data = JSON.parse(response);
window.location.href = data.redirect;
}
Upvotes: 1
Reputation: 950
The below code is working fine for me
return Json(new { Redirect = "/Account/Login" },JsonRequestBehavior.AllowGet);
and ajax success
success: function (response) {
window.location.href = response.Redirect ;
}
Upvotes: 1