按日期时间范围过滤MVC 5

时间:2016-12-08 12:37:20

标签: c# asp.net-mvc entity-framework razor asp.net-mvc-5

大家晚上好, 我回家了,任何人都可以在视图部分帮助我使用日期时间范围过滤器。 这是我的模特:

public class IndexVM
{
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public virtual ICollection<Order> Orders { get; set; }

}

我正在使用视图模型进行显示,现在这里是我的控制器:

public ActionResult Index(DateTime? start, DateTime? end)
    {

        var orders = db.Orders
            .Where(x => x.OrderStatus == 3
            && x.ClosedAt > start
            && x.ClosedAt < end)
            .OrderByDescending(x => x.LastUpdateAt)
            .ToList();

        IndexVM model = new IndexVM();
        model.StartDate = start;
        model.EndDate = end;
        model.Orders = orders;
        return View(model);
    }

现在我有一些问题。

以下是我的问题: 如何将开始和结束日期传递给控制器​​以获取具有已定义属性的订单? 这是我的观点以及我做错了什么?

@using (Html.BeginForm())
{
    <div class="form-horizontal">
        <div class="form-group form-group-sm">
            <div class="col-md-8">
                @Html.TextBoxFor(model => model.StartDate, "{0:MM/dd/yyyy}", new { @class = "date-picker form-control", @id = "start", @placeholder = "Start Date" })
            </div>
        </div>
        <div class="form-group form-group-sm">
            <div class="col-md-8">
                @Html.TextBoxFor(model => model.EndDate, "{0:MM/dd/yyyy}", new { @class = "date-picker form-control", @id = "end", @placeholder = "End Date" })
            </div>
        </div>
        <div class="form-group-sm">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" /> <span> </span>
            </div>
        </div>
    </div>
}

1 个答案:

答案 0 :(得分:2)

控制器

public ActionResult Index(DateTime? start, DateTime? end)
    {
  ViewBag.start = start;
            ViewBag.end = end;
        var orders = db.Orders
            .Where(x => x.OrderStatus == 3
            && x.ClosedAt > start
            && x.ClosedAt < end)
            .OrderByDescending(x => x.LastUpdateAt)
            .ToList();


        return View(orders);
    }

查看

@using (Html.BeginForm())
{
    <div class="form-horizontal">
        <div class="form-group form-group-sm">
            <div class="col-md-8">
               @Html.TextBox("start", null, new { @class = "form-control datepicker" }) 
            </div>
        </div>
        <div class="form-group form-group-sm">
            <div class="col-md-8">
               @Html.TextBox("end", null, new { @class = "form-control datepicker" })
            </div>
        </div>
        <div class="form-group-sm">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" /> <span> </span>
            </div>
        </div>
    </div>
}