Reputation: 11
I want to search the Details using date, it will not work, but searching by name works.
My controller code:
public ActionResult ProjectReport(string searchstring)
{
using (db)
{
// var v = db.Projects.ToList();
var Projects = from p in db.Projects
select p;
if (!String.IsNullOrEmpty(searchstring))
{
Projects = Projects.Where(p => p.ProjectTitle.Contains(searchstring));
}
var dateFilter = Convert.ToString(Request["sSearch_3"]);
if (dateFilter.Contains('~'))
{
//Split date range filters with ~
DateTime = dateFilter.Split('~')[0] == "" ?
DateTime.MinValue : Convert.ToDateTime(dateFilter.Split('~')[0]);
}
return View(Projects.ToList());
}
}
Upvotes: 0
Views: 7975
Reputation: 45
use paramater DateTime searchDate
instead of using string. Given your column also a date or datetime object, you can filter it right away.
Update: (after looking at your comment) If ActualSDate in Projects is datetime column. i.e the definition of Projects class is like this
public class Projects {
public DateTime ActualSDate { get; set; }
//other properties
}
in Controller
public ActionResult ProjectReport(DateTime searchDate)
{
var projects = db.Projects
.Where(c=>c.ActualSDate == searchDate)
.ToList();
return View(projects);
}
in View You must make sure there is an input with attribute name "searchDate" and the formatting is in correct date format if this is a HttpPost, or feeding the parameter with correct date format if this is a HttpGet
Update 2: You don't explained why it is not working. Maybe the date string is not match, anyway this is what I did many times in project, minimal version
View
@{
var fromDate = (DateTime)ViewBag.fromDate;
var toDate = (DateTime)ViewBag.toDate;
}
@using (Html.BeginForm("Action_Name", "Controller_Name", FormMethod.Get)) {
<div>From Date: @Html.TextBox("fromDate", string.Format("{0:dd MMM yyy}", fromDate), new { @class = "DatePicker" })</div>
<div>To Date: @Html.TextBox("toDate", string.Format("{0:dd MMM yyy}", fromDate), new { @class = "DatePicker" })</div>
<input type="submit" value="Search" />
}
Here, as you can see, I use FormMethod.Get, because this page function as searching page/ report
on master page, my jQuery DatePicker is instantiated like this
<script type="text/javascript">
$(document).ready(function () {
$(".DatePicker").datepicker({
dateFormat: 'dd M yy',
changeMonth: true,
changeYear: true,
});
});
</script>
So it will match my written date format like '3 Mar 2015'
In controller
public ActionResult ProjectReport(DateTime? fromDate, DateTime? toDate)
{
if (!fromDate.HasValue) fromDate = DateTime.Now.Date;
if (!toDate.HasValue) toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
if (toDate < fromDate) toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
var projects = db.Projects
.Where(c=>c.ActualSDate >= fromDate && c.ActualSDate < toDate)
.ToList();
return View(projects);
}
Upvotes: 1