2011-12-06 35 views
2

嗨我想重定向页面时,某些条件不是页面使用PartialViewResult方法。但我无法做到这一点。我的代码是像如下:在PartialViewResult()方法中重定向页面

public PartialViewResult Visit() 
{  
    int visit = 0; 
    if (base.IsLoggedIn() == true) 
    { 
     visit++; 
    } 
    else 
    { 
     // toDO redirect to home/index page 
    } 
} 
+0

并非所有的代码路径都返回结果。用户登录时应该发生什么? – Pieter

+0

不明白正在问什么。 – RayLoveless

回答

5

的代码片段会向您提供无法编译。您必须从所有代码路径返回结果。尝试是这样的:

public ActionResult Visit() 
{ 
    int visit = 0; 

    if (base.IsLoggedIn() == true) 
    { 
     visit++; 
     return PartialView(); 
    } 
    else 
    { 
     return RedirectToAction("ACTION_NAME_GOES_HERE"); 
    } 
} 

UPDATE:

我相信我现在明白你要完成的任务。如果ajax请求由未登录的用户发出,您希望浏览器重定向用户。我建议修改你的操作方法如下:

public ActionResult Visit() 
{ 
    int visit = 0; 

    if (base.IsLoggedIn()) 
    { 
     visit++; 
     // whatever else needs to be done 
     return PartialView(); 
    } 
    else 
    { 
     // Note that this could be done using the Authorize ActionFilter, using 
     // an overriden Authorize ActionFilter, or by overriding OnAuthorize(). 
     if (!base.IsLoggedIn()) 
      return new HttpUnauthorizedResult(); 
    } 
} 

假设你在你的web.config配置了,响应将是302重定向这是不是你在这种情况下想要的东西。见菲尔哈克的博客文章,说明此项ASP.NET行为如何防止和401未授权的响应可以返回:

http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

然后,假设你使用jQuery发出AJAX请求,您可以处理401响应:

$.ajax({ 
    url: '/your_controller/visit', 
    type: 'GET', 
    statusCode: { 
     200: function (data) { 
      // data = your partialview 
     }, 
     401: function (data) { 
      location.href = '/the_path/to_redirect/to'; 
     } 
    } 
}); 
+0

但在我的senerio我不能使用ActionResult –

+0

我很好奇......为什么不能在你的场景中使用ActionResult? –

+0

以及我打电话给这个方法作为通过ajax请求的用户控制 –

-3
else 
{ 
    return RedirectToAction("Index.aspx"); 
} 
+0

Response.Redirect不适用于ASP.NET MVC。 – slfan

+1

我不能使用RedirectToAction或ActionResult这个senerio。我只能通过使用PartialViewResult来重定向。但我不知道如何去做? –

0

而不是使用一个局部视图,你应该考虑使用OnActionExecuting或类似的,因为这种共同的逻辑并不在视图/控制器的归属。例如:

[AttributeUsage(AttributeTargets.All)] 
public sealed class RecordLoggedInCountAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      visit++; 
     } 
     else 
     { 
      filterContext.HttpContext.Response.Redirect("http://google.com"); 
     } 
    } 
} 

然后装点你想记录下这与[RecordLoggedInCount]

2

不知道我完全理解这个问题的任何控制器/动作,但是这可能帮助别人,因为它为我工作。

else 
{ 
    Response.Redirect("~/default.aspx"); 
    return null; 
} 
+0

这适用于我的场景。好奇的是,如果有人读到这个,这种方法有什么问题吗? – RLH