简体   繁体   English

ASP.NET MVC 5中的日期范围搜索过滤器功能?

[英]Date range search filter functionality in asp.net mvc 5?

Good evening everyone, I hope, anyone can help my with Date time range filter on view part. 大家晚上好,我希望任何人都可以在视图部分帮助我进行日期时间范围过滤。 Here is my model: 这是我的模型:

public class Student
{
    public int ID { get; set; }
    public string StudentName { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
    public DateTime CurrentDate { get; set; }
    public Student()
    {
        CurrentDate = DateTime.Now;
    }
}

I'm using view models for display, now here is my controller: 我正在使用视图模型进行显示,现在是我的控制器:

    public ActionResult Index(DateTime? startdate, DateTime? enddate)
    {
        var rangeData = db.Students.Where(x => x.CurrentDate >= startdate && x.CurrentDate <= enddate).ToList();

        return View(rangeData);
    }

Now I have some problems with view as well as in controller. 现在我在视图以及控制器方面都有一些问题。

Here is My QUESTION: How to pass start and end date to controller to get orders with defined properties? 这是我的问题:如何将开始日期和结束日期传递给控制器​​以获取具有已定义属性的订单? Here is My View and what I'm doing wrong? 这是我的观点,我做错了什么?

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Index", "Students", FormMethod.Get))
{
    <fieldset>
        <legend>Search criteria</legend>
        @Html.Label("StartDate", "Start Date:")
        <input class="startdate" id="startdate" name="startdate" type="date" value="">
        @Html.Label("enddate", "End Date:")
        <input class="startdate" id="enddate" name="enddate" type="date" value="">
        <input type="submit" value="Apply" />
    </fieldset>
} 


<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.StudentName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MobileNo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.StudentName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MobileNo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Course.CourseName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

Providing a placeholder attribute to your input fields to guide user on the date format expected is one option you can use since this seems like a date format issues. 在您的输入字段中提供占位符属性,以引导用户了解所需的日期格式是您可以使用的一种选择,因为这似乎是日期格式问题。 Another option is to use a date picker control which will automatically set the date in the right format. 另一种选择是使用日期选择器控件,它将自动以正确的格式设置日期。

However, if you want to give your users the flexibility to input date in any format of their choice with any separator including "/", "-" or just space, here is some tip 但是,如果您想让用户灵活地以他们选择的任何格式输入日期,并用任何分隔符(包括“ /”,“-”或仅空格)输入,以下是一些提示

      public ActionResult Index(string startdate = null, string enddate = null)
    {
        if (startdate != null && enddate != null)
        {
            //this will default to current date if for whatever reason the date supplied by user did not parse successfully

            DateTime start = DateManager.GetDate(startdate) ?? DateTime.Now;

            DateTime end = DateManager.GetDate(enddate) ?? DateTime.Now;

            var rangeData = db.Students.Where(x => x.CurrentDate >= start && x.CurrentDate <= end).ToList();

            return View(rangeData);
        }
        return View();
    }


      public class DateManager
    {
        /// <summary>
        /// Use to prevent month from being overritten when day is less than or equal 12
        /// </summary>
      static  bool IsMonthAssigned { get; set; }



        public static DateTime? GetDate(string d)
        {
            char[] splitsoptions = { '/', '-', ' ' };
            foreach (var i in splitsoptions)
            {
                var y = 0;
                var m = 0;
                var day = 0;
                if (d.IndexOf(i) > 0)
                {
           try{
                    foreach (var e in d.Split(i))
                    {


                        if (e.Length == 4)
                        {
                            y = Convert.ToInt32(e);

                            continue;
                        }
                        if (Convert.ToInt32(e) <= 12 && !IsMonthAssigned)
                        {
                            m = Convert.ToInt32(e);
                            IsMonthAssigned = true;
                            continue;
                        }
                        day = Convert.ToInt32(e);


                    }

                    return new DateTime(y, m, day);
            }catch
           { 
            //We are silent about this but we  could set a message about wrong date input in ViewBag    and display to user if this  this method returns null
            }
                }
            }
            return null;


        }
   // Another overload. this will catch more date formats without manually checking as above

     public static DateTime? GetDate(string d, bool custom)
        {
            CultureInfo culture = new CultureInfo("en-US");

            string[] dateFormats =
            {
                "dd/MM/yyyy", "MM/dd/yyyy", "yyyy/MM/dd", "yyyy/dd/MM", "dd-MM-yyyy", "MM-dd-yyyy", "yyyy-MM-dd",
                "yyyy-dd-MM", "dd MM yyyy", "MM dd yyyy", "yyyy MM dd", "yyyy dd MM", "dd.MM.yyyy", "MM.dd.yyyy",
                "yyyy.MM.dd", "yyyy.dd.MM","yyyyMMdd","yyyyddMM","MMddyyyy","ddMMyyyy"
            };//add your own to the array if any

            culture.DateTimeFormat.SetAllDateTimePatterns(dateFormats, 'Y');

            if (DateTime.TryParseExact(d, dateFormats, culture, DateTimeStyles.None, out var date))
                return date;

            return null;


        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM