簡體   English   中英

從asp.net mvc中的操作方法返回URL

[英]Return to a url from an action method in asp.net mvc

我正在使用asp.net mvc。

我有與“文檔”列表關聯的鏈接...單擊鏈接時,將調用操作方法以將文檔添加到收藏夾列表中。

在單擊“添加收藏夾”鏈接之前,如何在操作方法中返回同一頁面? 原因是我想維護具有分頁等的querystring參數

例如:

我的頁面

第1頁,共3頁

Document1 [添加到收藏夾](調用操作方法的鏈接)

Document2 [添加到收藏夾](調用操作方法的鏈接)

Document3 [添加到收藏夾](調用操作方法的鏈接)

Document4 [添加到收藏夾](調用操作方法的鏈接)

分頁是使用querystring參數在url中維護的。

當他們單擊添加時,我希望能夠維護該URL,因為它應該考慮到其所在的頁碼

您不能僅將當前頁面添加到action參數嗎?

public ActionResult AddFavourite(int? page)
{
   // generate your paged into based on page parameter
   return View(whatever_your_paged_view_is);
}

一種可能的方法是在文檔列表中的每個鏈接中包括所需的QueryStrings 您將通過ViewData將所需的查詢字符串傳遞給顯示文檔列表的視圖。

<% foreach(var doc in Model) { %>
    <%= ActionLink(doc.Title, "AddtoFavorites", new { Page = ViewData["PageNumber"], Query = ViewData["Query" }) %>
<% } %>

或類似的東西。

然后在操作方法中,將文檔添加到“收藏夾”中:

public ActionResult AddToFavorites(int documentID, int page, string query)
{
     // Do the work to add the document to favorites
     return RedirectToAction("ActionName", new { Page = page, Query = query}); // where "ActionName" is the name of the action that the user was on before they got here
}

另一種方法是將分頁信息存儲在TempData中,但是如果您希望用戶單擊多個鏈接,那會使事情特別復雜。

如果使用javascript,請調用javascript:history.back()

您可以使用Request.UrlReferrer來獲取先前的URL。 它是http協議的一部分,並由瀏覽器作為http標頭發送。 請記住,如果它與請求一起發送並且可能並不總是存在,則取決於瀏覽器/客戶端的實現。

根據我的最佳選擇是添加您的參數,以直接分頁到鏈接。

我將在一個額外的參數returnUrl發送頁面,.NET團隊自己在AccountController也使用此模式:

<%= Html.ActionLink("LINKNAME", "ACTION", new { id = "DOCID", returnUrl = Request.Url.PathAndQuery } ) %>

現在,您的操作將類似於:

public ActionResult ACTION(int id, string returnUrl)
{
     //do some stuff
     return Redirect(returnUrl);
}

暫無
暫無

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

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