How do I search between two dates using c# - c#

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

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

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);

Related

Why I can't pass this model to a controller in ASP.NET MVC [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 6 years ago.
Why i can't pass this model to a controller in ASP.NET MVC?
This is my View:
#model Pro.WebUI.ViewModels.DataItemVm
<div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstSetList.FirstOrDefault().Name)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstSetList.FirstOrDefault().Amount)
</th>
</tr>
#foreach (var item in Model.FirstSetList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Amount)
</td>
</tr>
}
</table>
<hr/>
<div>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.FirstSetList)
<input type="submit" value="Confirm"/>
}
</div>
</div>
After I click Confirm button - this method receives model with Count = 0;
public ActionResult FirstSet(DataItemVm model)
{
...
}
Of course my ViewModel DataItemVm has list:
public class DataItemVm
{
public List<FirstSetViewModel> FirstSetList { get; set; }
}
So it looks like that problem is only at view. Maybe BeginForm should be in other place? However HiddenFor should send be enough to send this model.
Change #foreach cycle to for - ASP.NET MVC uses indexers to generate correct ids and names for elements, so you should use #Html.TextBoxFor(x=>x.Array[index]) to correctly generate html for your collections.
This cycle:
#foreach (var item in Model.FirstSetList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Amount)
</td>
</tr>
}
Should instead look like this:
#for (var i = 0; i < Model.FirstSetList.Length; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.FirstSetList[i].Name)
#Html.HiddenFor(model => model.FirstSetList[i].Name) //otherwise name won't be returned to controller
</td>
<td>
#Html.TextBoxFor(model=> model.FirstSetList[i].Amount)
</td>
</tr>
}
Another issue is - markup for the data that you want to be sent to the controller should be put inside #using (Html.BeginForm()){//put it here} block.
Check out this post about model binding in ASP.NET MVC:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Can I modify multiple items in a BeginForm section in a Razor/MVC view [duplicate]

This question already has answers here:
Multiple checkboxes in razor (using foreach)
(3 answers)
Closed 7 years ago.
I would like to edit a list of items and save them all together in the same submit. Is it possible? If so, how?
I have the following piece of code, but it does not give the wanted result. Or otherwise I don't know what to write for the counterpart in the controller.
#using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.Id)
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Value)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Value)
</td>
</tr>
}
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Update Thanks to #Jonesopolis I came up with this working solution
#using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(modelItem => modelItem[i].Id)
#Html.DisplayFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].Value)
</td>
<td>
#Html.TextBoxFor(modelItem => modelItem[i].Value)
</td>
</tr>
}
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
For MyController
public class MyController : Controller
{
[HttpPost]
public ActionResult Save(IEnumerable<NameDoesNotMatter> newValues)
{
...
}
}
public class NameDoesNotMatter
{
public int Id { get; set; }
public decimal? Value { get; set; }
}
Now see if i can work out the thing with the templates. The link of #StephenMuecke should be sufficient
Update 2
Well that's wasn't that hard the code is now
#using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
#Html.EditorForModel()
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
And for Views/Shared/EditorTemplates/TypeOfModel.cshtml
#model TypeOfModel
<tr>
<td>
#Html.HiddenFor(item => item.Id)
#Html.DisplayFor(item => item.Name)
</td>
<td>
#Html.DisplayFor(item => item.Value)
</td>
<td>
#Html.TextBoxFor(item => item.Value)
</td>
</tr>
The controller remains the same
When you just show items using a for loop then the naming convention used in the resulting html tag doesn't match up with what MVC is expecting when it binds the model upon form submit. The easiest way to fix this is to use #Html.EditorFor and custom editor templates. Here are a couple of examples:
ASP.NET MVC DisplayTemplate and EditorTemplates for Entity Framework DbGeography Spatial Types
Extending Editor Templates for ASP.NET MVC

Model Properties passing as nulls to Action

I am trying to pass an item with the type "EmployeeDocument" to my action but all of values are coming back as nulls and I am not sure why. I have tried passing the entire model as well as just pieces and they are all null and I am not sure why this is happening.
Here is what my view looks like:
<table id="results-table" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>
<u>#Html.DisplayName("Title")</u>
</th>
<th>
<u>#Html.DisplayName("Document Type")</u>
</th>
<th>
<u>#Html.DisplayName("Created By")</u>
</th>
<th>
<u>#Html.DisplayName("Created Date")</u>
</th>
<th style="width: 180px;"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.DocumentType)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>View | #Html.ActionLink("Replace", "ReplaceEmployeeDocument", "Employee",new {title = item.Title, doctype = item.DocumentType, createdDate = item.CreatedDate,createdBy = item.CreatedBy, fullUrl = item.FullUrl}) | #Html.ActionLink("Delete", "DeleteEmployeeDocument",new {fileName = item.FullUrl, employeeNo = item.EmployeeNumber})</td>
</tr>
}
</tbody>
</table>
I am focusing on the replace action link in the table.
This is what my action looks like:
[HttpGet]
public ActionResult ReplaceEmployeeDocument(string title, string doctype, DateTime createdDate, string createdBy, string fullUrl)
{
var doc = new EmployeeDocument();
return PartialView(doc);
}
All of the parameters in the action are null. Is there a reason why these are like that?
You are trying to post back a collection of objects, in order for this to work you need to use a for loop and index the properties with hidden inputs as follows:
#using (Html.BeginForm("ReplaceEmployeeDocument", "Controller"))
{
#for(var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Title)
#Html.DisplayFor(m => m[i].Title)
</td>
<td>
#Html.HiddenFor(m => m[i].DocumentType)
#Html.DisplayFor(m => m[i].DocumentType)
</td>
<td>
#Html.HiddenFor(m => m[i].CreatedBy)
#Html.DisplayFor(m => m[i].CreatedBy)
</td>
<td>
#Html.HiddenFor(m => m[i].CreatedDate)
#Html.DisplayFor(m => m[i].CreatedDate)
</td>
<td>View | <input type="submit" value="Replace"/></td>
</tr>
}
}
You also need a corresponding post method that accepts the model being passed back:
[HttpPost]
public ActionResult ReplaceEmployeeDocument(EmployeeDocument model)
{
var doc = new EmployeeDocument();
return PartialView(doc);
}
You dont seem to be using any #Html.EditorFor which would generate input fields, and you dont have any form or javascript that would send your arguments in either GET or POST method. Therefore none of your fields are sent to the method in the controller. You should wrape the code inside the foreach in a
#Html.BeginForm() {}

cshtml view if inside of foreach inside of else

I'm trying to display records in my view. I only want to display records that don't have a null value for the TABLE_NUMBER1 field. I've set this up, but am having a weird issue where it won't recognize the closing tag for the else, only the foreach and if. Specifically, if I add a closing tag for the else, it recognizes it as the closing tag for the entire razer section (aka it's gold).
#if (Model.Count() == 0)
{
<tbody>
<tr>
<td colspan="7">
No Records match search criteria
</td>
</tr>
</tbody>
}
else{
foreach (var item in Model)
{
var hiderows = #Html.DisplayFor(modelItem => item.TABLE_NUMBER1).ToString();
if (hiderows != null)
{
<tbody>
<tr>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.PNTR_MAX)</p>
</td>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.EFFECTIVE_DATE1)</p>
</td>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.BANK_ROUTING_NUMBER)</p>
</td>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.TAX_ID)</p>
</td>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.BANK_NAME)</p>
</td>
<td>
<p class="one">#Html.DisplayFor(modelItem => item.COMPANY_NAME1)</p>
</td>
<td>
#Html.ActionLink("Edit", "..\\Table9\\Edit", new { id = item.EFTID })
#Html.ActionLink("Details", "..\\Table9\\Details", new { id = item.EFTID })
#Html.ActionLink("Delete", "..\\Table9\\Delete", new { id = item.EFTID })
</td>
</tr>
</tbody>
}
}
}
This is wrong:
var hiderows = #Html.DisplayFor(modelItem => item.TABLE_NUMBER1);
change it to :
#Html.DisplayFor(modelItem => item.TABLE_NUMBER1)
if (item.TABLE_NUMBER1!= null)
{

select all tr of a table and send it to the controller using checkbox , in MVC 4

I want to use the Check box for selecting multiple users and sending the result to my controller.
At first I was only sending the number of mobile users to the controller but it became necessary to send more than the number, I need number and name user, my controller and my view are as follows:
Would somehow send the number and name for example?
#using (Html.BeginForm("Enviar", "Home")) {
<table id="myTable">
<thead>
<tr>
<th>
<input type="checkbox" />
</th>
<th>#Html.DisplayName("Nome")</th>
<th>#Html.DisplayName("CANCELADO")</th>
<th>#Html.DisplayName("Numero")</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
<input type="checkbox" name="CELULAR" value="#item.CELULAR" />
</td>
<td name="Nome">#Html.DisplayFor(modelItem => item.NOME)</td>
<td name="Email">#Html.DisplayFor(modelItem => item.CANCELADO)</td>
<td name="Celular" value="#item.CELULAR">#Html.DisplayFor(modelItem => item.CELULAR)</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Selecionar"/>
}
The controller that receives:
[HttpPost]
public ActionResult Enviar(String[] celular) {
.....
return View();
}
When posting collections, you must index them correctly. Therfore, you must use a for loop instead of a foreach.
Also, why does your HttpPost take a String[] and not your Model? First change that to be your model type.
Assuming your model is: #model List<YourType>
Change your HttpPost to take that:
[HttpPost]
public ActionResult Enviar(List<YourType> model) {
.....
return View();
}
Now we'll rewrite your foreach into a for and use the CheckBoxFor helper. Also, add HiddenFor fields for any properties you want to see on post:
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(m => m[i].CELULAR)
</td>
<td name="Nome">
#Html.HiddenFor(m => m[i].NOME)
#Html.DisplayFor(m => m[i].NOME)
</td>
<td name="Email">
#Html.HiddenFor(m => m[i].CANCELADO)
#Html.DisplayFor(m => m[i].CANCELADO)
</td>
<td name="Celular" value="#m[i].CELULAR">
#Html.DisplayFor(m => m[i].CELULAR)
</td>
</tr>
}

Categories