繁体   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