我需要在我的 asp.net mvc(C#) 应用程序的所有页面中维护查询字符串。
例如:
我会叫一个页面www.example.com?Preview=True
.无论我在 www.example.com
中单击哪个页面,都应该维护查询字符串.即当我点击 About us
页面在www.example.com
, url 应该是 www.example.com/AboutUs?Preview=True
我怎样才能做到这一点?什么是进行这种常见操作的最佳位置。?
最佳答案
也许您需要自定义路线?:
public class PreviewRoute : System.Web.Routing.Route
{
...
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
var preview = System.Web.HttpContext.Current.Session["Preview"];
if (!values.ContainsKey("Preview"))
values.Add("Preview", preview);
var path = base.GetVirtualPath(requestContext, values);
return path;
}
}
}
套装
Session["Preview"]
任何时候,您都可以通过 ?Preview=True
获得所有网址。 :System.Web.HttpContext.Current.Session.Add("Preview", true);
更新:
在 Global.asax.cs 中使用此路由:
routes.Add("Default",
new PreviewRoute("{controller}/{action}/{id}", new MvcRouteHandler()) {
Defaults = new RouteValueDictionary(
new { controller = "Home", action = "Index", id = "" }
)
}
);
代替:
routes.MapRouteLowercase(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
你也可以试试这个扩展:
public static class CustomRouteExtensions
{
public static void MapPreviewRoute(this RouteCollection routes, string name, string url, object defaults) {
routes.MapPreviewRoute(name, url, defaults, null);
}
public static void MapPreviewRoute(this RouteCollection routes, string name, string url, object defaults, object constraints) {
if (routes == null) {
throw new ArgumentNullException("routes");
}
if (url == null) {
throw new ArgumentNullException("url");
}
var route = new PreviewRoute(url, new MvcRouteHandler()) {
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints)
};
if (String.IsNullOrEmpty(name)) {
routes.Add(route);
}
else {
routes.Add(name, route);
}
}
}
在 Global.asax.cs 中:
routes.MapPreviewRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
关于asp.net-mvc - 在mvc中维护所有页面中的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789453/