[ASP.NET MVC] Redirect to View

在 ASP.NET MVC 網站,需通過 Controller 導向至不同的 View。然而實際的狀況很多,經常在不同的 Controller 之間導向 View。
以下三種寫法,應該可以解決多數情況。

(一) 使用 View( )

public class UserController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

這個寫法的缺點是:直接導到該頁面,不通過其所屬的 Controller
.

(二) 使用 RedirectToAction( )

(1) 非 Area

return RedirectToAction("Index", "Home", null);

(2) 在 Area 內,導向至 Area 外的 Controller

return RedirectToAction("Index", "Home", new { Area="" });

.

(三) 使用 Redirect( ) 導向至指定 URL

string virtualPath = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath;
HttpContext.Current.Response.Redirect(virtualPath + "Users/Login", true);

.
.

2 關於 “[ASP.NET MVC] Redirect to View” 的評論

發表留言