2017-05-05 83 views
0

我有一個索引操作,可以通過使用查詢字符串進行過濾。當我選擇一條記錄時,我將轉到詳細信息操作。從那裏我可以導航到與此記錄相關的其他操作,然後將我引導回「詳細信息」操作。我希望能夠保存索引頁面中的URL,該頁面將使查詢字符串參數保持不變。顯然,我不能直接使用Request.UrlReferrer來完成此操作,因爲如果上一個操作不是Index,它將不正確。我想出了一個解決方案,但我想知道是否有更好的方法。謝謝!保存查詢字符串Bewteen操作

public ActionResult Details(int? id) 
{ 
    var url = Request.UrlReferrer; 

    // Save URL if coming from the Employees/Index page 
    if (url != null && url.AbsolutePath == "/Employees") 
     Session.Add("OfficeURL", url.ToString()); 

    // Model Stuff 

    return View(); 
} 

詳細查看

@Html.ActionLink("Back to List", "Index", null, new { @href = Session["OfficeURL"] }) 

回答

1

你需要傳遞一個 「返回URL」 與您鏈接到其他視圖。本質:

Index.cshtml

@Html.ActionLink("View Details", "Details", "Foo", new { returnUrl = Request.RawUrl }) 

這將對把當前索引中的網址鏈接的查詢字符串的效果。然後,在你的其他操作,你會在ViewBag接受以此爲PARAM並存儲起來:

public ActionResult Details(int? id, string returnUrl = null) 
{ 
    ... 

    ViewBag.ReturnUrl = returnUrl; 
    return View(); 
} 

然後,在這些意見中,您將使用同樣的方式這ViewBag成員如上:

Details.cshtml

@Html.ActionLink("Click Me!", "Foo", "Foo", new { returnUrl = ViewBag.ReturnUrl }) 

當你準備要回去的索引,那麼,你會鏈接/重定向到,你已經繞過這一回URL。

+0

解決方案運行良好。我認爲這是處理此請求的最常見方法? – DrivenTooFar