asp.net-mvc-2 - 在 ASP.Net MVC 2 中的整个站点中持久化查询字符串参数

标签 asp.net-mvc-2 query-string asp.net-mvc-routing

http:www.site1.com/?sid=555

无论是发布表单还是单击链接,我都希望能够使 sid 参数和值保持不变。

如果用户导航到实现分页的 View ,则应在 sid 之后添加查询字符串中的其他参数。

http:www.site1.com/?sid=555&page=3

如何在 Asp.Net Mvc 2 中完成此操作?

[编辑]

我在上面提到的 url 将是应用程序的入口点,因此 sid 将包含在链接中。

在应用程序链接中,如:

<%= Html.ActionLink("Detail", "Detail", new { controller = "User", 
                                              id = item.UserId })%>

应该去:
http:www.site1.com/user/detail/3?sid=555

这个问题与 Dave 提到的不同,因为 querystring 参数在整个站点中持续存在。

最佳答案

首先,我想说如果值需要在整个 session 中保持不变,那么您应该将它存储在 Session 中并检查它在每个 Action 调用中是否仍然有效。这可以通过您添加到 Controller /所需操作的自定义操作属性来完成。如果需要该值,则在检查该值时,您可以重新定向到登录页面或类似页面(如果不存在或已过期)。

无论如何,这就是说我认为我可以让它发挥作用。我的第一个想法是创建一个自定义操作过滤器属性,该属性获取查询字符串的值并将其存储在 session 中 OnActionExecuting然后 OnResultExecuted会将键添加回查询字符串。但是由于 Request 中的 QueryString 是只读集合,因此您不能直接执行此操作。

那么,您现在可以使用什么?

选项 #1 - 手动将其添加到对 Html.ActionLink() 的所有调用

或者 ...

选项 #2 - 覆盖 ActionLink 的一个版本,它会自动为您添加值。这可以像这样实现。不过我不建议这样做。

从自定义属性开始。

public class PersistQueryStringAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var sid = filterContext.RequestContext.HttpContext.Request.QueryString["sid"];

        if (!string.IsNullOrEmpty(sid))
        {
            filterContext.RequestContext.HttpContext.Session["sid"] = sid;
        }

        base.OnActionExecuting(filterContext);
    }
}

所有这些都是检查所需 key 的请求查询字符串,如果可用,则将其添加到 session 中。

然后您将 ActionLink 扩展方法覆盖为您自己的方法之一,该方法将值添加到其中。
public static class HtmlHelperExtensions
{
    public static MvcHtmlString ActionLink<TModel>(this HtmlHelper<TModel> helper, string text, string action, string controller, object routeValues)
    {
        var routeValueDictionary = new RouteValueDictionary(routeValues);

        if (helper.ViewContext.RequestContext.HttpContext.Session["sid"] != null)
        {
            routeValueDictionary.Add("sid", helper.ViewContext.RequestContext.HttpContext.Session["sid"]);    
        }

        return helper.ActionLink(text, action, controller, routeValueDictionary, null);
    }
}

在将要调用的每个操作上应用属性(或将其应用到 Controller ),例如:
[PersistQueryString]
public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    return View();
}

备注

当查询值被放入 session 时,它将在 session 的生命周期内被应用。如果您想检查该值是否存在并且每个请求是否相同,您将需要在属性覆盖方法中进行一些检查。

最后

我纯粹是将其作为“可以做到”的练习来完成的。我强烈建议反对它。

关于asp.net-mvc-2 - 在 ASP.Net MVC 2 中的整个站点中持久化查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835296/

相关文章:

jquery - 韦杰莫日期选择器最大日期

asp.net-mvc - MVC 3 ViewModel 模式问题(使用 RAZOR)

javascript - 在 javascript 中调用我的 wcf 服务时出现 404 - 我缺少什么?

c# - MVC 路由与部分类

c# - MVC View 与表单绑定(bind)并在同一页面显示数据

asp.net-mvc - Asp.net - MVC1 与 MVC2

javascript - 使用 javascript 检查查询字符串是否有值

PHP:如何检查总数。网址中的参数?

asp.net-mvc-4 - 如何在 ASP.Net MVC4 中的 cshtml 文件中获取 session 值

c# - 显示时间填充 Stackoverflow 和 Facebook 是如何做的 - C#