前情提要:
在c# mvc EF模式下 普通的列表展示页面,采用form提交的,后台视同request对象接收,如果涉及到时间搜索的情况,经常会搞错,现在明确一下怎么做。
一:Request
/// <summary>
/// 发票信息
/// </summary>
public class InvoiceInforRequest : Request
{
/// <summary>
/// 创建开票时间
/// </summary>
public DateTime? AddDateStart { get; set; }
public DateTime? AddDateEnd { get; set; }
}
public class Request : ModelBase
{
public Request()
{
PageSize = ;
} public int Top
{
set
{
this.PageSize = value;
this.PageIndex = ;
}
} public int PageSize { get; set; }
public int PageIndex { get; set; }
}
public class ModelBase
{
public ModelBase()
{
CreateDate = DateTime.Now;
} public virtual int ID { get; set; }
public virtual DateTime CreateDate { get; set; }
public virtual int CreateStaffID { get; set; }
public virtual string CreateStaffName { get; set; }
}
这里使用的就是InvoiceInforRequest中的AddDateStart 和AddDateEnd
二:页面form提交
<form class="form-inline">
<div class="form-group">
<label class="control-label">
起止日期:</label>
@Html.TextBox("AddDateStart", ViewData["AddDateStart"], new { @class = "form-control Wdate", @onclick = "WdatePicker()", @style = "width:100px;" })
<span style="margin: 0 5px">-</span>
@Html.TextBox("AddDateEnd", ViewData["AddDateEnd"], new { @class = "form-control Wdate", @onclick = "WdatePicker()", @style = "width:100px;" })
</div>
<button class="btn btn-info">
<span class="glyphicon glyphicon-search"></span> 查询</button>
</form>
三:Controller方法
public ActionResult Index(InvoiceInforRequest request)
{
request.CreateDate = new DateTime();
ViewData.Add("AddDateStart", DateTime.Now.AddMonths(-).ToCnDataString());
ViewData.Add("AddDateEnd", DateTime.Now.ToCnDataString());
//获取发票列表
//Stopwatch sw = new Stopwatch();
//sw.Start();
var invoiceInforList = this.OMService.GetInvoiceInforList(request);
//sw.Stop();
//var sss = sw.ElapsedMilliseconds;
return View(invoiceInforList);
}
四:BILL
/// <summary>
/// 发票信息列表
/// </summary>
public IEnumerable<InvoiceInfor> GetInvoiceInforList(InvoiceInforRequest request)
{
using (var dbContext = new OMDbContext())
{
IQueryable<InvoiceInfor> invoiceinforiqueryable = dbContext.InvoiceInfor.Include("TaxControl").Include("Invoice").Include("Invoice.Branch");
if (request.Status != (int)EnumInvoiceInforStatus.NotOpen)
{
if (request.AddDateStart != null)
{
invoiceinforiqueryable = invoiceinforiqueryable.Where(i => i.BillingDate >= request.AddDateStart);
}
if (request.AddDateEnd != null)
{
//结束时间加了23小时和59分钟
//linq的语法总是不支持addhours、convert 可能是我版本的问题,mvc 4.0
request.AddDateEnd = Convert.ToDateTime(request.AddDateEnd).AddHours().AddMinutes();
invoiceinforiqueryable = invoiceinforiqueryable.Where(i => i.BillingDate <= request.AddDateEnd);
}
}
return invoiceinforiqueryable.OrderByDescending(i => i.ID).ToPagedList(request.PageIndex, request.PageSize);
}
}
五:结论:
因为这种模式下的提交,时间选择插件最后选择的时间是只到天:“yyyy-MM-dd” ,而不是“yyyy-MM-dd hh:mm:ss”,但是数据库(sql)中的时间格式是datetime
所以要在时间查询的时候,最后想查的是今天的,但是结束时间应该是今天的最后一分钟或者一秒钟。
谢谢,看懂了就懂了,看不懂的,也希望能帮到你。