thatthing
thatthing

Reputation: 676

datetime format in MVC 4

I have the following registerdate table in my db.

public Nullable<System.DateTime> registerdate { get; set; }

Because of my model is auto-generated and it says "Manual changes to this file may cause unexpected behavior in your application" i dont want to touch it.

So this is my controller:

        public ActionResult Index(string searchBy, string search, DateTime? search2)
    {
        if (searchBy == "ID")
        {
            return View(db.students.Where(x => x.studentid == search).ToList());
        }
        else if (searchBy == "grade")
        {
            return View(db.students.Where(x => x.grades == search).ToList());
        }
        else if (searchBy == "registerdate")
        {
            return View(db.students.Where(x => x.registerdate == search2).ToList());
        }
        else
        {
            return View(db.students.Where(x => x.studentname.Contains(search)).ToList());
        }
    }

and i use following code in my view:

        <p>
        @using (Html.BeginForm("Index", "Home", FormMethod.Get))
        {
            <b>Search by:</b> @Html.RadioButton("searchby", "ID", true) <text>StudentID</text>
            @Html.RadioButton("searchby", "grade") <text>Grade</text>
            @Html.RadioButton("searchby", "registerdate") <text>RegisterDate</text>
            <br /><br />
            @Html.TextBox("search") <input type="submit" value="Search" />
        }
        </p>

and to display:

        @Html.DisplayFor(modelItem => item.registerdate)

So basically i can perform search by id, grade or studentname. But it doesnt work for registerdate. When i search by registerdate, it brings no results.

Any idea why i am not getting any results if i search by registerdate?

Upvotes: 0

Views: 553

Answers (1)

Tommy
Tommy

Reputation: 39807

Ah, the DateTime comparison issue. I am assuming when creating / registering a student, you are setting RegiseterDate to something like DateTime.Now

student.RegisterDate = DateTime.Now();

As a result, the register date is stored as 4/20/2014 09:38:27. Now, when you send a date from the web interface (using a date picker or something similar), your search2 variable is set to 4/20/2014 00:00:00. You can clearly see that the first April 20th DateTime is not equal to the second April 20th DateTime.

Typically, you could compare DateTime variables where you only care about the date portion using student.RegisterDate.Date == search2, but EF cannot convert that .Date() to SQL. So, the easiest way is to compare the entire range of the day using something like below:

    //search2 == 4/20/2014 00:00:00
    var endDate = search2.Value.AddDays(1);
    //endDate == 4/21/2014 00:00:00
    return View(db.students.Where(x => x.registerdate >= search2 
&& x.registerdate < endDate).ToList());
    //return all students where registerdate is between 4/20/2014 00:00:00 and 4/21/2014 00:00:00.

Upvotes: 2

Related Questions