簡體   English   中英

如何通過ASP.NET MVC中的超鏈接返回上一個視圖?

[英]How do I go back to the previous view through a hyperlink in ASP.NET MVC?

我有模型(POCO實體),例如StudentCourseStandard等。我有相應的控制器,例如StudentController等。每個模型都有一個視圖Index ,該視圖在DB中顯示所有相應實體的列表。 例如, StudentController.Index()返回/Student/Index視圖。 但是,如果數據庫中沒有學生記錄,則不返回Index視圖,而是重定向到Navigation控制器的Empty操作方法,即NavigationController.Empty() ,該方法返回/Navigation/Empty視圖。 對所有模型實體類都完成此操作。

現在,在空白頁上,我希望有一個超鏈接可以返回到上一頁。 因此,我在NavigationController類中創建了一個名為GoBack()的操作方法,在該方法中,我重定向到了上一個視圖。 但是,如何使用此操作方法訪問有關上一頁內容的信息? 還是有更好的方法來做到這一點? 我不想使用后退按鈕。

就我而言,這里有兩條路線。 您可以使用會話或應用程序緩存來存儲訪問過的頁面,然后使用RedirectToActionGoBack()操作中獲取該頁面(例如,通過存儲路由)。

但是,也許更好,更無狀態的方法是通過使視圖模型具有最后使用的控制器和操作的兩個屬性來呈現超鏈接。 然后,您可以從調用/Navigation/Empty操作的操作結果中傳遞它們(沒有任何記錄時)。

視圖模型

public class NavigationVM
{
public string LastAction {get;set;}
public string LastController {get;set;}
}

導航控制器動作

public ActionResult Empty(string lastAction, string lastController)
{
var vm = new NavigationVM()
{
LastAction = lastAction,
LastController = lastController
}
return View(vm);
}

視圖

@model = Namespace.NavigationVM

@Html.ActionLink("LinkName", Model.LastAction, Model.LastController)

編輯

如果然后您需要找出從何處調用了學生控制器(在您的示例中),您可以使用相同的方法進行操作。 即:使用額外的路由值將鏈接呈現給StudentsController

StudentController:

public ActionResult Index(string lastAction, string lastController)

{
     .... // no students
return RedirectToAction("Empty", "Navigation", new RouteValueDictionary(new { lastAction = "Index", lastController= "Student"}));

}

具有到學生控制器的超鏈接的視圖(分別使用將這個視圖呈現為lastActionlastController的動作和控制器):

@Html.ActionLink("Get students", "Index", "Student", new { lastAction= "Index", lastController = "CallingController" }, null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM