【发布时间】:2014-08-04 04:53:15
【问题描述】:
我想从控制器中检索 JSOn 数据并将其设置为 window.location。
在 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;
}
});
});
在控制器中:
[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);
}
当我运行它时,为 jquery 检索 json 数据 {"redirect":"/Account/Login"}。并重定向到http://localhost:2478/undefined(返回未定义的重定向)。
如果我返回Json(Url.Action("Login", "Account") , JsonRequestBehavior.AllowGet);,它会重定向到http://localhost:2478/%22/Account/Login%22
如何从控制器中检索 url 数据?
【问题讨论】:
-
把它放在一个变量中,然后从 json 中返回,例如: var url="/Account/Login" ..... return Json(new { redirect = url }, JsonRequestBehavior.AllowGet);
-
谢谢,我使用了一个变量,但它再次返回
undefined:( -
alert(responseData.redirect);...是说未定义???
-
返回空警报。
-
数据类型:Json -> json?试试看。
标签: jquery asp.net-mvc json asp.net-mvc-4