2011-12-06 68 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