asp.net mvc怎么按时间段查询 下面这段代码是查询代码 如何在C层和V层实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了asp.net mvc怎么按时间段查询 下面这段代码是查询代码 如何在C层和V层实现相关的知识,希望对你有一定的参考价值。

/// 动态搜索类new
/// ?int UserID=0 用户ID
/// ?DateTime BeginDate=DateTime.Now 开始时间
/// ?DateTime EndDate=DateTime.Now 结束时间
/// ?int AccountID=0 账号类型
/// ?string OrderFeild="Order Desc" 排序字段和方式
///
/// </param>
/// <param name="iPageIndex">页码</param>
/// <param name="iPageSize">每页显示条数</param>
/// <returns></returns>
public PagedList<Finance_WithdrawalDetail> GetWithdrawalDetail(dynamic dySearch, int iPageIndex, int iPageSize)

try

var queryBuilder = QueryBuilder.Create<Finance_WithdrawalDetail>();
ExpandoObject doSearch = dySearch;
var Keys = ((IDictionary<String, Object>)doSearch).Keys;
if (Keys.Contains("UserID")) //用户ID

queryBuilder.Equals(n => n.UserID, (int)dySearch.UserID);

if (Keys.Contains("BeginDate")) //开始时间

queryBuilder.Between(n => n.AddTime, (DateTime)dySearch.BeginDate, DateTime.MaxValue);

if (Keys.Contains("EndDate")) //结束时间

queryBuilder.Between(n => n.AddTime, DateTime.MinValue, (DateTime)dySearch.EndDate);


string strOrder = string.Empty;
if (Keys.Contains("OrderFeild") && !string.IsNullOrEmpty(dySearch.OrderFeild)) //排序字段和方式

strOrder = dySearch.OrderFeild;

else

strOrder = "ID Desc";


var list = db.Finance_WithdrawalDetail.Where(queryBuilder.Expression).myorder(strOrder);

return new PagedList<Finance_WithdrawalDetail>(list, iPageIndex, iPageSize);

catch (Exception ex)

return null;

c 层 调用

viewdata["data"]= PagedList<Finance_WithdrawalDetail> GetWithdrawalDetail(....);
return view();

v层

@{var data = viewdata["data"] as PagedList<Finance_WithdrawalDetail>;
<table>

@ foreach(var d in data)

........<td>@d.......</td>

</table>

追问

在V层不是直接显示出来的 是要求输入时间段 点击查询按钮查询

追答

1、做一个 form ,加入时间选择框 提交到c c 层里面接受到参数后 根据参数去过滤记录

然后输出的记录就是过滤的了

2、全部json ajax把记录请求到前台,数据不多的情况下,点击查询的时候 只在客户端过滤 ,利用js操作 也行

3、建议用ext 等js 框架来实现gird的展示 ,他的例子中也有一些教程来展示如何请求数据,也有过滤方面的东西

4、asp.net mvc 我最为推荐的 是你使用 telerik ,可以搜索下 ,看下这个开源的扩展框架,可能使你的开发起来更容易 ,可以看下他的例子和源码,分页 查询什么的都是小问题了,目前asp.net mvc这块可能只有它这块支持好点

参考技术A 将你查询得到的 PagedList<Finance_WithdrawalDetail> 传递给视图就可以了
在视图时循环输出信息
参考技术B 好高深,我晕菜了

Asp.Net MVC的路由

  通过前面几篇博文的介绍,现在我们已经清楚了asp.net请求管道是怎么一回事了,这篇博文来聊聊MVC的路由。

  其实MVC的请求管道和Asp.Net请求管道一样,只是MVC扩展了UrlRoutingModule的动作。我们知道MVC网站启动后第一个请求会执行Global.asax文件中的Application_Start方法,完成一些初始化工作,其中就会注册路由,先来看下面一张图,该图可以直观的展示了MVC执行的流程。

技术图片技术图片

   结合上图,我们一起来看看代码是如何实现路由的注册的。

 protected void Application_Start()
 
      AreaRegistration.RegisterAllAreas();
      RouteConfig.RegisterRoutes(RouteTable.Routes);
 

 public class RouteConfig
 
     public static void RegisterRoutes(RouteCollection routes)
     
        routes.IgnoreRoute("resource.axd/*pathInfo");

        routes.MapRoute(
            name: "Default",
            url: "controller/action/id",
            defaults: new  controller = "Home", action = "Index", id = UrlParameter.Optional 
        );
     
 

RouteCollection通过MapRoute扩展方法拿着Url来创建Route并注册到RouteCollection其中,这一点我们通过源码可以看到该方法是如何操作的,该方法通过new一个MvcRouteHandler来创建Route。MvcRouteHandler创建了MvcHandler。紧接着继续往下执行,创建HttpApplication实例,执行后续事件,在PostResolveRequestCache事件去注册UrlRouteModule的动作。

// System.Web.Mvc.RouteCollectionExtensions
/// <summary>Maps the specified URL route and sets default route values, constraints, and namespaces.</summary>
/// <returns>A reference to the mapped route.</returns>
/// <param name="routes">A collection of routes for the application.</param>
/// <param name="name">The name of the route to map.</param>
/// <param name="url">The URL pattern for the route.</param>
/// <param name="defaults">An object that contains default route values.</param>
/// <param name="constraints">A set of expressions that specify values for the <paramref name="url" /> parameter.</param>
/// <param name="namespaces">A set of namespaces for the application.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="routes" /> or <paramref name="url" /> parameter is null.</exception>
public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)

    if (routes == null)
    
        throw new ArgumentNullException("routes");
    
    if (url == null)
    
        throw new ArgumentNullException("url");
    
    Route route = new Route(url, new MvcRouteHandler())
    
        Defaults = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(defaults), 
        Constraints = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(constraints), 
        DataTokens = new RouteValueDictionary()
    ;
    ConstraintValidation.Validate(route);
    if (namespaces != null && namespaces.Length > 0)
    
        route.DataTokens["Namespaces"] = namespaces;
    
    routes.Add(name, route);
    return route;
using System;
using System.Web.Mvc.Properties;
using System.Web.Routing;
using System.Web.SessionState;
namespace System.Web.Mvc

    /// <summary>Creates an object that implements the IHttpHandler interface and passes the request context to it.</summary>
    public class MvcRouteHandler : IRouteHandler
    
        private IControllerFactory _controllerFactory;
        /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class.</summary>
        public MvcRouteHandler()
        
        
        /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class using the specified factory controller object.</summary>
        /// <param name="controllerFactory">The controller factory.</param>
        public MvcRouteHandler(IControllerFactory controllerFactory)
        
            this._controllerFactory = controllerFactory;
        
        /// <summary>Returns the HTTP handler by using the specified HTTP context.</summary>
        /// <returns>The HTTP handler.</returns>
        /// <param name="requestContext">The request context.</param>
        protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
        
            requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext));
            return new MvcHandler(requestContext);
        
        /// <summary>Returns the session behavior.</summary>
        /// <returns>The session behavior.</returns>
        /// <param name="requestContext">The request context.</param>
        protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext)
        
            string text = (string)requestContext.RouteData.Values["controller"];
            if (string.IsNullOrWhiteSpace(text))
            
                throw new InvalidOperationException(MvcResources.MvcRouteHandler_RouteValuesHasNoController);
            
            IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory();
            return controllerFactory.GetControllerSessionBehavior(requestContext, text);
        
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        
            return this.GetHttpHandler(requestContext);
        
    
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Web.Security;
namespace System.Web.Routing

    /// <summary>Matches a URL request to a defined route.</summary>
    [TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
    public class UrlRoutingModule : IHttpModule
    
        private static readonly object _contextKey = new object();
        private static readonly object _requestDataKey = new object();
        private RouteCollection _routeCollection;
        /// <summary>Gets or sets the collection of defined routes for the ASP.NET application.</summary>
        /// <returns>An object that contains the routes.</returns>
        public RouteCollection RouteCollection
        
            get
            
                if (this._routeCollection == null)
                
                    this._routeCollection = RouteTable.Routes;
                
                return this._routeCollection;
            
            set
            
                this._routeCollection = value;
            
        
        /// <summary>Disposes of the resources (other than memory) that are used by the module.</summary>
        protected virtual void Dispose()
        
        
        /// <summary>Initializes a module and prepares it to handle requests.</summary>
        /// <param name="application">An object that provides access to the methods, properties, and events common to all application objects in an ASP.NET application.</param>
        protected virtual void Init(HttpApplication application)
        
            if (application.Context.Items[UrlRoutingModule._contextKey] != null)
            
                return;
            
            application.Context.Items[UrlRoutingModule._contextKey] = UrlRoutingModule._contextKey;
            application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);
        
        private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
        
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContextBase context = new HttpContextWrapper(httpApplication.Context);
            this.PostResolveRequestCache(context);
        
        /// <summary>Assigns the HTTP handler for the current request to the context.</summary>
        /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
        /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Web.Routing.RouteData.RouteHandler" /> property for the route is null.</exception>
        [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")]
        public virtual void PostMapRequestHandler(HttpContextBase context)
        
        
        /// <summary>Matches the HTTP request to a route, retrieves the handler for that route, and sets the handler as the HTTP handler for the current request.</summary>
        /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
        public virtual void PostResolveRequestCache(HttpContextBase context)
        
            RouteData routeData = this.RouteCollection.GetRouteData(context);
            if (routeData == null)
            
                return;
            
            IRouteHandler routeHandler = routeData.RouteHandler;
            if (routeHandler == null)
            
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0]));
            
            if (routeHandler is StopRoutingHandler)
            
                return;
            
            RequestContext requestContext = new RequestContext(context, routeData);
            context.Request.RequestContext = requestContext;
            IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
            if (httpHandler == null)
            
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[]
                
                    routeHandler.GetType()
                ));
            
            if (!(httpHandler is UrlAuthFailureHandler))
            
                context.RemapHandler(httpHandler);
                return;
            
            if (FormsAuthenticationModule.FormsAuthRequired)
            
                UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
                return;
            
            throw new HttpException(401, SR.GetString("Assess_Denied_Description3"));
        
        void IHttpModule.Dispose()
        
            this.Dispose();
        
        void IHttpModule.Init(HttpApplication application)
        
            this.Init(application);
        
    

  到此,路由的注册动作也就告一段落。那么在理解了MVC的路由后,可以做什么呢?我们可以对路由做一些我们自己的扩展。

  可以从三个层面来扩展路由:

  一、在MapRoute范围内进行扩展,这种扩展只是在扩展正则表达式

 public static void RegisterRoutes(RouteCollection routes)
        
            routes.IgnoreRoute("resource.axd/*pathInfo");//忽略路由
                                                             //mvc路由规则下的扩展
            routes.IgnoreRoute("Handler/*pathInfo");
            routes.MapRoute(
             name: "About",
             url: "about",//不区分大小写
             defaults: new  controller = "First", action = "String", id = UrlParameter.Optional 
            );//静态路由
            routes.MapRoute("TestStatic", "Test/action", new  controller = "Second" );//替换控制器

            routes.MapRoute(
                    "Regex",
                     "controller/action_Year_Month_Day",
                     new  controller = "First", id = UrlParameter.Optional ,
                     new  Year = @"^\\d4", Month = @"\\d2", Day = @"\\d2" 
                       );//正则路由

            routes.MapRoute(
                name: "Default",
                url: "controller/action/id",
                defaults: new  controller = "Home", action = "Index", id = UrlParameter.Optional ,
                namespaces: new string[]  "Jesen.Web.Controllers" 
            );
          
        

 

  二、通过继承RouteBase来扩展Route,这种扩展可以随意的定制规则,而不仅仅是表达式

    /// <summary>
    /// 直接扩展route
    /// </summary>
    public class MyRoute : RouteBase
    
        /// <summary>
        /// 解析路由信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        
       //此处可以根据自己的需求做一些路由的配置,例如拒绝某个浏览器的访问,检测到Chrome浏览器,则直接跳转到某个url
if (httpContext.Request.UserAgent.IndexOf("Chrome/69.0.3497.92") >= 0) RouteData rd = new RouteData(this, new MvcRouteHandler()); rd.Values.Add("controller", "Pipe"); rd.Values.Add("action", "Refuse"); return rd; return null; /// <summary> /// 指定处理的虚拟路径 /// </summary> /// <param name="requestContext"></param> /// <param name="values"></param> /// <returns></returns> public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) return null;

接着在RouteConfig和Global.asax中注册该路由

public static void RegisterMyRoutes(RouteCollection routes)

    routes.Add(new MyRoute());


protected void Application_Start()

    RouteConfig.RegisterMyRoutes(RouteTable.Routes);

  

  三、扩展Handler,不一定是MvcHandler,可以是我们熟悉的IHttpHandler

 

    /// <summary>
    /// 扩展IRouteHandler /// </summary>
    public class MyRouteHandler : IRouteHandler
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        
            return new MyHttpHandler(requestContext);
        
    

    /// <summary>
    /// 扩展IHttpHandler
    /// </summary>
    public class MyHttpHandler : IHttpHandler
    
        public MyHttpHandler(RequestContext requestContext)
        
            
        

        public void ProcessRequest(HttpContext context)
        
            string url = context.Request.Url.AbsoluteUri;
            context.Response.Write((string.Format("当前地址为:0", url)));
            context.Response.End();
        

        public virtual bool IsReusable
        
            get
            
                return false;
            
        
    

RouteConfig.cs文件中配置路由

  public static void RegisterMyMVCHandler(RouteCollection routes)
  
      routes.Add(new Route("MyMVC/*Info", new MyRouteHandler()));
  

Global中注册路由

 RouteConfig.RegisterMyMVCHandler(RouteTable.Routes);

运行看结果

技术图片

 

以上是关于asp.net mvc怎么按时间段查询 下面这段代码是查询代码 如何在C层和V层实现的主要内容,如果未能解决你的问题,请参考以下文章

asp.net mvc3 linq 多表查询怎么把返回的集合在页面循环输出

在使用asp.net mvc查询时候的分页

使用多个字段过滤/搜索 - ASP.NET MVC

ASP.NET MVC 5 缓存 CSS 和 JS 文件

Asp.Net MVC的路由

asp.net mvc中使用linq to sql查询数据集(IQueryable类型) 怎么用foreach循环去数据集的数据?