Reputation: 2184
I have created a very simple search form in my MVC application which allows the user to search for a string term and returnt he results. I would like to let my users search between two dates but I'm not sure how I'd program that.
Here is my code so far. As you'll notice this is only for searching for a string that is passed into the controller as a parameter. I have started writing the code for the date pickers but I've gotten stuck.
View
<h2>Search</h2>
@using (Ajax.BeginForm("Search", "Search", new AjaxOptions
{
OnSuccess = "Success",
OnFailure = "Failure",
UpdateTargetId = "test",
InsertionMode = InsertionMode.Replace
}))
{
<table class="table">
<tr>
<td><label>Vessel Name</label></td>
<td>@Html.TextBox("term",null, new { @class = "k-textbox" })</td>
</tr>
<tr>
<td>
<label>From</label>
@(Html.Kendo().DatePicker()
.Name("date_from")
.Value(DateTime.Today)
)
</td>
<td>
<label>To</label>
@(Html.Kendo().DatePicker()
.Name("date_to")
.Value(DateTime.Today)
)
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Search" />
</td>
</tr>
</table>
}
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>MMSI</th>
<th>Created</th>
</tr>
</thead>
<tbody id="test">
@Html.Partial("_results")
</tbody>
</table>
Controller
public ActionResult Search(string term, DateTime date_from, DateTime date_to)
{
var vessels = (from o in db.vessels
select o);
if (!String.IsNullOrEmpty(term))
{
vessels = vessels.Where(s =>
s.vessel_name.Contains(term) ||
s.vessel_location.Contains(term) ||
s.vessel_mmsi.Contains(term));
}
return PartialView("_results", vessels);
}
Partial View Since I'm using ajax to update a target ID I return the results as in a partial view using the 'replace' insertion method.
@model IEnumerable<Multiple_Table_Post.Models.vessel>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.vessel_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.vessel_location)
</td>
<td>
@Html.DisplayFor(modelItem => item.vessel_mmsi)
</td>
<td>
@Html.DisplayFor(modelItem => item.created)
</td>
</tr>
}
As you'll notice I have started putting the date pickers in place but I don't know how to write the c# to allow me to search between them. I'm passing them into the method as datetime parameters but after is where I'm totally stuck.
Many thanks
Upvotes: 1
Views: 1025
Reputation: 99957
var vessels = (from o in db.vessels
where o.vessel_date => date_from
&& o.vessel_date =< date_to
&& ( term==null
|| o.vessel_name.Contains(term)
&& o.vessel_location.Contains(term)
&& o.vessel_mmsi.Contains(term))
select o);
Upvotes: 0
Reputation: 967
You could do this in either of the LINQ queries you have shown.
var vessels= (from o in db.vessels
where (o.created>= date_from && o.created<= date_to)
select o);//I have not tested this.
More Info:
C# Linq Where Date Between 2 Dates
You can also filter the dates in the second LINQ query as seen in the other answers
Upvotes: 1