我从javascript调用了ActionResult,如下所示:
function checkSessionNewContribute(){
if (@MountainBooks.Common.ProjectSession.UserID != 0) {
window.location.href = "../Book/ContributeNewBook"
}
else{
$.ajax({
url: "@Url.Action("redirectToLogin", "Home")"
});
}
}
我需要从这个ActionResult传递TempData:
public ActionResult redirectToLogin(){
TempData["Login"] = Resource.Messages.LoginRequired;
return RedirectToAction("Index","Login");
}
这是我的索引动作:
public ActionResult Index() {
string email = null;
string password = null;
if (Request.Cookies["Login"] != null){
email = Request.Cookies["Login"].Values["LogedEmail"];
password = General.DecryptCipherTextToPlainText(Request.Cookies["Login"].Values["LogedPwd"]);
}
ViewBag.ErrorMessage = TempData["wrongPassword"];
ViewBag.Login = TempData["Login"];
UserModel userModel = new UserModel();
userModel.Email = email;
userModel.Password = password;
ViewData["LoginModel"] = userModel;
userModel = new UserModel();
userModel.Occupations = (_occupationService.GetAllOccupation());
ViewData["RegisterModel"] = userModel;
return View();
}
调用索引操作,调试器也进入.cshtml文件,Index Action返回View(),但页面没有被重定向。是因为我使用了$ .ajax()吗?还有另一种方法吗?
答案 0 :(得分:1)
在else
内,您可以使用window.location.href
,如下所示,
function checkSessionNewContribute()
{
if (@MountainBooks.Common.ProjectSession.UserID != 0) {
window.location.href = "/Book/ContributeNewBook/"
}
else {
window.location.href = "/Home/redirectToLogin/";
//or
//var url = '@Url.Action("redirectToLogin", "Home")';
//window.location.href = url;
}
}
ajax()方法用于执行AJAX(异步HTTP)请求。 此方法主要用于向服务器发出请求。无法通过ajax调用重定向到另一个页面。