I'm new to MVC. Using the scaffolding mechanism I have managed to create CRUD operations on the database table. This works well with working on a single MVC Model at a time (Mapped to a single Model). I want to implement add & edit of a List into database (will be empty list initially), the user should be able to add as many number of items as he need and then submit the data to the database. I want this list to be of dynamic length, so that when user edits the data he should be able to add few more new elements into the Model also deleting few individual Model. I couldn't find proper resource to come up with a solution. Little help will be much Appreciated.
Scenario - Person can have multiple Addresses or Person will not be having any addresses. How to add multiple Address by adding addresses into the view and how to perform edit on those? If one of the Address needs to be deleted then how to do so?
Thank you.
Here is My View:
#model MVC.Models.PersonDetailsViewModel
#{
ViewBag.Title = "AddorEdit";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="container">
<div id="personDetails" class="row">
#Html.HiddenFor(model => model.personModel.PersonId, new { #id = "personId" })
<div class="form-group">
<div class="col-md-2">
<label>First Name</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Last Name</label>
<div style="display:inline;">
#Html.EditorFor(model => model.personModel.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Date of Birth</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.DateOfBirth, new { #id = "dob", htmlAttributes = new { #class = "form-control date-picker" } })
#Html.ValidationMessageFor(model => model.personModel.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Height</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Height, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Height, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Weight</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Weight, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Weight, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Location</label>
<div style="display:inline">
#Html.EditorFor(model => model.personModel.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.personModel.Location, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<div id="tabs" class="panel panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">Address</li>
<li>Insuarance</li>
<li>Emergency Contacts</li>
</ul><br />
</div>
<div class="tab-content panel-body">
<div id="tabs-1" class="tab-pane fade in active">
<div style="height:22px">
<a class="btn btn-default" id="btnAdd" style="float:right"><span class="glyphicon glyphicon-plus-sign"></span> Add New Row</a>
</div>
<br />
<div id="mainContent">
<div id="addressDiv">
<div class="col-md-11">
#*#Html.Partial("_Address", Model.addressModel);*#
#{
Html.RenderAction("AddressPartialView", "Person");
}
</div>
<a id="closeAddress" style="margin-top:33px" class="col-md-1 closeLink"><i class="glyphicon glyphicon-trash" style="color:red"></i></a>
</div>
</div>
</div>
<div id="tabs-2" class="tab-pane fade">
#Html.HiddenFor(model => model.insuranceModel.InsuranceId, new { #id = "insuranceId" })
<div class="col-md-4">
<label>Health Plan</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.HealthPlan, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.HealthPlan, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Health Plan Type</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.HealthPlanType, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.HealthPlanType, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Card Number</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.insuranceModel.CardNumber, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.insuranceModel.CardNumber, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-3" class="tab-pane fade">
#Html.HiddenFor(model => model.emergencyContactModel.EmergencyContactId, new { #id = "emergencyContactId" })
<div class="col-md-3">
<label>Contact Patient</label>
<div style="display:inline">
#{
List<SelectListItem> personItems = new List<SelectListItem>();
personItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
personItems.Add(new SelectListItem { Text = "1", Value = "1" });
personItems.Add(new SelectListItem { Text = "2", Value = "2" });
personItems.Add(new SelectListItem { Text = "3", Value = "3" });
personItems.Add(new SelectListItem { Text = "4", Value = "4" });
}
#Html.DropDownListFor(model => model.emergencyContactModel.ContactPersonId, personItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.ContactPersonId, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Relationship Type</label>
<div style="display:inline">
#{
List<SelectListItem> relationshipItems = new List<SelectListItem>();
relationshipItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
relationshipItems.Add(new SelectListItem { Text = "Father", Value = "Father" });
relationshipItems.Add(new SelectListItem { Text = "Mother", Value = "Mother" });
relationshipItems.Add(new SelectListItem { Text = "Son", Value = "Son" });
relationshipItems.Add(new SelectListItem { Text = "Daughter", Value = "Daughter" });
relationshipItems.Add(new SelectListItem { Text = "Guardian", Value = "Guardian" });
}
#Html.DropDownListFor(model => model.emergencyContactModel.RelationshipType, relationshipItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.RelationshipType, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Contact Number</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.emergencyContactModel.ContactNumber, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.ContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Email Id</label>
<div style="display:inline">
#Html.TextBoxFor(model => model.emergencyContactModel.EmailId, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.emergencyContactModel.EmailId, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<br />
<div class="col-md-12">
<input type="submit" value="Save" class="btn btn-default" style="margin-top:10px" />
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
And here are my Controller Methods:
public ActionResult AddressPartialView()
{
var _model = new PersonDetailsViewModel();
return PartialView("_Address", _model.addressModel);
}
//To load the data into the form - for editing
public ActionResult AddorEdit(int id = 0)
{
if (id == 0)
{
var myModel = new PersonDetailsViewModel();
return View(myModel);
}
else
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.GetAsync("Person/" + id.ToString()).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.GetAsync("Address/" + id.ToString()).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.GetAsync("Insurance/" + id.ToString()).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.GetAsync("EmergencyContact/" + id.ToString()).Result;
var personJsonString = responsePerson.Content.ReadAsStringAsync();
var deserializedPerson = JsonConvert.DeserializeObject<IEnumerable<MvcPersonModel>>(personJsonString.Result);
var addressJsonString = responseAddress.Content.ReadAsStringAsync();
var deserializedAddress = JsonConvert.DeserializeObject<IEnumerable<MvcAddressModel>>(addressJsonString.Result);
var insuranceJsonString = responseInsurance.Content.ReadAsStringAsync();
var deserializedInsurance = JsonConvert.DeserializeObject<IEnumerable<MvcInsuranceModel>>(insuranceJsonString.Result);
var emergencyContactJsonString = responseEmergencyContact.Content.ReadAsStringAsync();
var deserializedEmergencyContact = JsonConvert.DeserializeObject<IEnumerable<MvcEmergencyContactModel>>(emergencyContactJsonString.Result);
var _ViewModel = new PersonDetailsViewModel();
_ViewModel.personModel = deserializedPerson.FirstOrDefault();
_ViewModel.addressModel = deserializedAddress.FirstOrDefault();
_ViewModel.insuranceModel = deserializedInsurance.FirstOrDefault();
_ViewModel.emergencyContactModel = deserializedEmergencyContact.FirstOrDefault();
return View(_ViewModel);
}
}
//Posting data to the database
[HttpPost]
public ActionResult AddorEdit(PersonDetailsViewModel viewModel)
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.PostAsJsonAsync("Person", viewModel.personModel).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.PostAsJsonAsync("Address", viewModel.addressModel).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.PostAsJsonAsync("Insurance", viewModel.insuranceModel).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.PostAsJsonAsync("EmergencyContact", viewModel.emergencyContactModel).Result;
return RedirectToAction("Index");
}
I'm using Web API for the backend process. I have added a delete and Add New Row button in the view for Address tab. For now it is working with just a single Model, I wanted to know how to implement it for a Dynamic list, So as to A Person can have 'n' number of Addresses and he can edit whichever he want and also delete based on AddressId. I know the code seems quite low rated. Just want to know the syntax and semantics on how to proceed with working on List. Sorry for Messing up things. Thank you.
Got a solution from Matt lunn.
Follow this link :-
https://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/
It is implemented by using custom HtmlHelper Extension and creating Html.EditorForMany().
Thanks a lot for the trick Matt Lunn. Works Exactly How I wanted. :)
I have a question about PagedList. I have a grid of data that I can filter using dropdownlist and checkbox. It works well. I use "PagedList", which allows me to display only 10 row per page in my grid of data. It works well when I don't use filter. When I select an item in my dropdownlist for example, the filter works well in the first page but if I click on the 2nd page the filter doesn't work anymore. To filter data, I use method Post and ViewModel. What can I do?
Thanks!
Here is my view:
#using (Html.BeginForm("Index", "Missions", FormMethod.Post))
{
<section>
<h3>Localisation</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirGeoSelected, "Direction geo", htmlAttributes: new { #class = "control-label col-md-8" })
<div class="col-md-4">
#Html.DropDownListFor(model => model.DirGeoSelected, Model.DirGeoList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirGeoSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
<div class="form-group">
#Html.LabelFor(model => model.ProgrammeIdSelected, "Programme", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.ProgrammeIdSelected, Model.Programme, "All", htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProgrammeIdSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryIdSelected, "Pays", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.CountryIdSelected, Model.Country, "All", htmlAttributes: new { onchange = "form.submit();", #class = "form-control"/*, data_url = Url.Action("GetCountries")*/ })
#Html.ValidationMessageFor(model => model.CountryIdSelected, "", new { #class = "text-danger" })
</div>
</div>
</section>
<section>
<h3>Personne</h3>
</section>
<section>
#*
<h3>Date</h3>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateStart", new {#class = "datepicker"})
</div>
</div>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateEnd", new { #class = "datepicker"})
</div>
</div>
*#
</section>
<section>
<h3>Type</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Priority</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Décision</h3>
<div class="col-md-12">
#Html.EditorFor(x => x.Decison)
</div>
</section>
<section>
<h3>Equipe</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirectionIdSelected, "Direction", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.DirectionIdSelected, Model.DirectionList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirectionIdSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
</section>
}
</nav>
<div id="content" class="container">
<h2>Missions</h2>
#* #using (Html.BeginForm("Index", "Missions", FormMethod.Get))
{
#Html.TextBox("searching")
<input type="submit" value="submit" />
}
*#
<p class="newmission">
<input type="button" class="btn btn-info" value="Nouvelle Mission" onclick="location.href='#Url.Action("Create", "Missions")'" />
</p>
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.ActionLink("Pays", "Index",
new { SortOrder = Model.SortCountry})
</th>
<th class="col-md-1">
#Html.ActionLink("Date", "Index",
new { SortOrder = ViewBag.ListorderDate,
/*SelectedDesk = ViewBag.ListorderPays,
SelectedProgramme = ViewBag.ListorderDate,*/
})
</th>
<th class="col-md-2">
Personne
</th>
<th class="col-md-10">
Missions
</th>
<th class="col-md-10">
</th>
</tr>
#foreach (var item in Model.OnePageOfMissions)
{
<tr>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.decision)
</td>
<td class="col-md-2">
#Html.DisplayFor(modelItem => item.organization_hi_country.name_en)
</td>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.asked_date)
</td>
<td class="col-md-2"></td>
<td class="col-md-10">
<span class="typemission">Mission</span> #Html.DisplayFor(modelItem => item.list_type.name_en, new { #class = "typemission" }) : #Html.DisplayFor(modelItem => item.list_nature.name_en, new { #class = "typemission" })
<div>
<!-- les boutons d'actions -->
details
</div>
<!-- le contenu masqué -->
<section id="#Html.DisplayFor(modelItem => item.id)" class="collapse">
<div class="well">
<p><em>Statut: </em>#Html.DisplayFor(modelItem => item.list_statut.name_en)</p>
<p><em>Durée: </em>#Html.DisplayFor(modelItem => item.duration) jours</p>
<p><em>Flexibilité: </em>#Html.DisplayFor(modelItem => item.list_flexibility.name_en) </p>
<p><em>Priorité: </em>#Html.DisplayFor(modelItem => item.list_priority.name_en) </p>
<p><em>Commentaires: </em>#Html.DisplayFor(modelItem => item.comments) </p>
</div>
</section>
</td>
<td class="col-md-10">
#Html.ActionLink("Edit", "Create", new { id = item.id })
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
#Html.PagedListPager((IPagedList)Model.OnePageOfMissions, page => Url.Action("Index", new { searchItem = ViewBag.searchItem, page }))
</table>
Here is my controller:
namespace MissionsDF.Controllers
{
public class MissionsController : Controller
{
private Missions_devEntities db = new Missions_devEntities();
// GET: /Missions/
public ActionResult Index(string SortOrder, int? page)
{
IndexViewModel model = new IndexViewModel();
//Affichage de la liste des Programmes
model.Programme = GetProgrammes();
//Tri des pays:
model.SortCountry = String.IsNullOrEmpty(SortOrder) ? "ListorderPays_desc" : "";
model.missionsList = db.missions_supportmission.ToList();
switch (SortOrder)
{
case "ListorderPays_desc":
model.missionsList = model.missionsList.OrderByDescending(s => s.organization_hi_country.name_en);
break;
default:
model.missionsList = model.missionsList.OrderBy(s => s.organization_hi_country.name_en);
break;
}
//Pagination
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10); // will only contain 10 products max because of the pageSize(equel to 10)
model.OnePageOfMissions = onePageOfMissions;
//Ischecked
var allDecisions = db.list_decision.ToList();//returns List<list_decision>
var checkBoxListItems = new List<CheckBoxListItem>(); //nouvelle instance de la classe checkboxlist
foreach (var decison in allDecisions)
{//On assigne les valeurs "id", "display" et "is checked" à la variable checkboxlistitem
checkBoxListItems.Add(new CheckBoxListItem()
{
ID = decison.decision_id,
Display = decison.name_en,
IsChecked = false //On the add view, no decision are selected by default
});
}
model.Decison = checkBoxListItems;
return View(model);
}
private List<SelectListItem> GetProgrammes()
{
return db.organization_programme
.Select(x => new SelectListItem
{
Value = x.prog_id,
Text = x.name_en
})
.ToList();
}
//POST: /Missions/Index
[HttpPost]
public ActionResult Index(IndexViewModel model, int? page)
{
//Filtres sur Programme et Country
if (ModelState.IsValid)
{
var pageNumber = page ?? 1;
var selecteddecision = model.Decison.Where(x => x.IsChecked).Select(x => x.ID);
//Si selecteddecision n'est pas null
//Si Programme n'est pas null et que country est null
if (!(selecteddecision.IsAny()))
{
if (!String.IsNullOrEmpty(model.ProgrammeIdSelected) && String.IsNullOrEmpty(model.CountryIdSelected))
{
var onePageOfMissions = db.missions_supportmission
.Where(a => a.programme_id == model.ProgrammeIdSelected)
.OrderBy(a => a.programme_id)
.Select(s => s).ToPagedList(pageNumber, 10);
model.OnePageOfMissions = onePageOfMissions;
}
//Si Country est null
else if (!String.IsNullOrEmpty(model.CountryIdSelected))
{
model.OnePageOfMissions = db.missions_supportmission
.Where(a => a.country_id == model.CountryIdSelected)
.OrderBy(a => a.country_id)
.Select(s => s).ToPagedList(pageNumber, 10);
if (model.missionsList != null)
{
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10);
model.OnePageOfMissions = onePageOfMissions;
}
}
//Sinon on affiche tout
else
{
model.OnePageOfMissions = db.missions_supportmission
.OrderBy(a => a.programme_id)
.Select(s => s).ToPagedList(pageNumber, 10);
}
}
else
{
foreach (var item in selecteddecision)
{
//Si Programme n'est pas null et que country est null
if (!String.IsNullOrEmpty(model.ProgrammeIdSelected) && String.IsNullOrEmpty(model.CountryIdSelected))
{
model.OnePageOfMissions = db.missions_supportmission
.Where(a => a.programme_id == model.ProgrammeIdSelected)
.Where(a => a.decision == item)
.OrderBy(a => a.programme_id)
.Select(s => s).ToPagedList(pageNumber, 10);
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10);
model.OnePageOfMissions = onePageOfMissions;
}
//Si Country est null
else if (!String.IsNullOrEmpty(model.CountryIdSelected))
{
model.OnePageOfMissions = db.missions_supportmission
.Where(a => a.country_id == model.CountryIdSelected)
.Where(a => a.decision == item)
.OrderBy(a => a.country_id)
.Select(s => s).ToPagedList(pageNumber, 10);
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10);
model.OnePageOfMissions = onePageOfMissions;
}
//Sinon on affiche tout
else
{
model.OnePageOfMissions = db.missions_supportmission
.Where(a => a.decision == item)
.OrderBy(a => a.programme_id)
.Select(s => s).ToPagedList(pageNumber, 10);
}
}
}
}
var allDecisions = db.list_decision.ToList();//returns List<list_decision>
var checkBoxListItems = new List<CheckBoxListItem>(); //nouvelle instance de la classe checkboxlist
foreach (var decison in allDecisions)
{//On assigne les valeurs "id", "display" et "is checked" à la variable checkboxlistitem
checkBoxListItems.Add(new CheckBoxListItem()
{
ID = decison.decision_id,
Display = decison.name_en,
});
}
model.Decison = checkBoxListItems;
//Affichage en cascade liste de programmes + liste pays
model.Programme = GetProgrammes();
model.Country = db.organization_hi_country
.Where(a => a.prog_id == model.ProgrammeIdSelected)
.Select(x => new SelectListItem
{
Value = x.country_id,
Text = x.name_en
}).ToList();
return View(model);
}
1) If you are willing to revamp and modify your code both server side and client-side, I recommend following instructions mentioned at this tutorial
2) In case you want to use Post method then, following changes may help you:
In your server side code, wherever you are assigning an object to 'ViewBag.searchItem', try using TempData["searchItem"] in place of it. And when accessing it on View page, also use TempData["searchItem"] wherever you are accessing 'ViewBag.searchItem' with appropriate casting.
While I suppose your server side code is working, client side html may work as shown below, with form tag wrapped around entire HTML..
#using (Html.BeginForm("Index", "Missions", FormMethod.Post))
{
<section>
<h3>Localisation</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirGeoSelected, "Direction geo", htmlAttributes: new { #class = "control-label col-md-8" })
<div class="col-md-4">
#Html.DropDownListFor(model => model.DirGeoSelected, Model.DirGeoList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirGeoSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
<div class="form-group">
#Html.LabelFor(model => model.ProgrammeIdSelected, "Programme", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.ProgrammeIdSelected, Model.Programme, "All", htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProgrammeIdSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryIdSelected, "Pays", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.CountryIdSelected, Model.Country, "All", htmlAttributes: new { onchange = "form.submit();", #class = "form-control"/*, data_url = Url.Action("GetCountries")*/ })
#Html.ValidationMessageFor(model => model.CountryIdSelected, "", new { #class = "text-danger" })
</div>
</div>
</section>
<section>
<h3>Personne</h3>
</section>
<section>
#*
<h3>Date</h3>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateStart", new {#class = "datepicker"})
</div>
</div>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateEnd", new { #class = "datepicker"})
</div>
</div>
*#
</section>
<section>
<h3>Type</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Priority</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Décision</h3>
<div class="col-md-12">
#Html.EditorFor(x => x.Decison)
</div>
</section>
<section>
<h3>Equipe</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirectionIdSelected, "Direction", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.DirectionIdSelected, Model.DirectionList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirectionIdSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
</section> <div id="content" class="container">
<h2>Missions</h2>
<p class="newmission">
<input type="button" class="btn btn-info" value="Nouvelle Mission" onclick="location.href='#Url.Action("Create", "Missions")'" />
</p>
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.ActionLink("Pays", "Index",
new { SortOrder = Model.SortCountry})
</th>
<th class="col-md-1">
#Html.ActionLink("Date", "Index",
new { SortOrder = ViewBag.ListorderDate,
/*SelectedDesk = ViewBag.ListorderPays,
SelectedProgramme = ViewBag.ListorderDate,*/
})
</th>
<th class="col-md-2">
Personne
</th>
<th class="col-md-10">
Missions
</th>
<th class="col-md-10">
</th>
</tr>
#foreach (var item in Model.OnePageOfMissions)
{
<tr>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.decision)
</td>
<td class="col-md-2">
#Html.DisplayFor(modelItem => item.organization_hi_country.name_en)
</td>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.asked_date)
</td>
<td class="col-md-2"></td>
<td class="col-md-10">
<span class="typemission">Mission</span> #Html.DisplayFor(modelItem => item.list_type.name_en, new { #class = "typemission" }) : #Html.DisplayFor(modelItem => item.list_nature.name_en, new { #class = "typemission" })
<div>
<!-- les boutons d'actions -->
details
</div>
<!-- le contenu masqué -->
<section id="#Html.DisplayFor(modelItem => item.id)" class="collapse">
<div class="well">
<p><em>Statut: </em>#Html.DisplayFor(modelItem => item.list_statut.name_en)</p>
<p><em>Durée: </em>#Html.DisplayFor(modelItem => item.duration) jours</p>
<p><em>Flexibilité: </em>#Html.DisplayFor(modelItem => item.list_flexibility.name_en) </p>
<p><em>Priorité: </em>#Html.DisplayFor(modelItem => item.list_priority.name_en) </p>
<p><em>Commentaires: </em>#Html.DisplayFor(modelItem => item.comments) </p>
</div>
</section>
</td>
<td class="col-md-10">
#Html.ActionLink("Edit", "Create", new { id = item.id })
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
#Html.PagedListPager((IPagedList)Model.OnePageOfMissions, page => Url.Action("Index", new { page }))
</table>}
Thanks, I found the solution. I decided to use only get method.
In my controller I have this:
public ActionResult Index(string SortOrder, int? page, string ProgrammeIdSelected)
{
IndexViewModel model = new IndexViewModel();
//Affichage de la liste des Programmes
model.Programme = GetProgrammes();
//Tri des pays:
model.SortCountry = String.IsNullOrEmpty(SortOrder) ? "ListorderPays_desc" : "";
model.ProgrammeIdSelected = ProgrammeIdSelected;
model.missionsList = db.missions_supportmission.ToList();
switch (SortOrder)
{
case "ListorderPays_desc":
model.missionsList = model.missionsList.OrderByDescending(s => s.organization_hi_country.name_en);
break;
default:
model.missionsList = model.missionsList.OrderBy(s => s.organization_hi_country.name_en);
break;
}
//Pagination
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10); // will only contain 10 products max because of the pageSize(equel to 10)
model.OnePageOfMissions = onePageOfMissions;
//Ischecked
var allDecisions = db.list_decision.ToList();//returns List<list_decision>
var checkBoxListItems = new List<CheckBoxListItem>(); //nouvelle instance de la classe checkboxlist
foreach (var decison in allDecisions)
{//On assigne les valeurs "id", "display" et "is checked" à la variable checkboxlistitem
checkBoxListItems.Add(new CheckBoxListItem()
{
ID = decison.decision_id,
Display = decison.name_en,
IsChecked = false //On the add view, no decision are selected by default
});
}
//Si Programme n'est pas null et que country est null
if (!String.IsNullOrEmpty(ProgrammeIdSelected))
{
model.OnePageOfMissions = db.missions_supportmission
.Where(a => a.programme_id == ProgrammeIdSelected)
.OrderBy(a => a.programme_id)
.Select(s => s).ToPagedList(pageNumber, 10);
}
return View(model);
}
An d in my View I have this:
#using (Html.BeginForm("Index", "Missions", FormMethod.Get))
{
<section>
<h3>Localisation</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirGeoSelected, "Direction geo", htmlAttributes: new { #class = "control-label col-md-8" })
<div class="col-md-4">
#Html.DropDownListFor(model => model.DirGeoSelected, Model.DirGeoList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirGeoSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
<div class="form-group">
#Html.LabelFor(model => model.ProgrammeIdSelected, "Programme", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.ProgrammeIdSelected, Model.Programme, "All", htmlAttributes: new {onchange = "form.submit();", #class = "form-control"})
#Html.ValidationMessageFor(model => model.ProgrammeIdSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryIdSelected, "Pays", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.DropDownListFor(model => model.CountryIdSelected, Model.Country, "All", htmlAttributes: new { onchange = "form.submit();", #class = "form-control"/*, data_url = Url.Action("GetCountries")*/ })
#Html.ValidationMessageFor(model => model.CountryIdSelected, "", new { #class = "text-danger" })
</div>
</div>
</section>
<section>
<h3>Personne</h3>
</section>
<section>
#*
<h3>Date</h3>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateStart", new {#class = "datepicker"})
</div>
</div>
<div class="form-group">
<div class="col-md-8">
#Html.TextBox("SelectedDateEnd", new { #class = "datepicker"})
</div>
</div>
*#
</section>
<section>
<h3>Type</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Priority</h3>
<div class="col-md-12 form-check">
#Html.CheckBox("Support", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Mission Support", htmlAttributes: new { #class = "control-label" })
#Html.CheckBox("Autre", true, new { onchange = "form.submit();", #class = "form-check-input" })
#Html.Label("Autre", htmlAttributes: new { #class = "control-label" })
</div>
</section>
<section>
<h3>Décision</h3>
<div class="col-md-12">
#Html.EditorFor(x => x.Decison)
</div>
</section>
<section>
<h3>Equipe</h3>
#*
<div class="form-group">
#Html.LabelFor(model => model.DirectionIdSelected, "Direction", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.DirectionIdSelected, Model.DirectionList, htmlAttributes: new { onchange = "form.submit();", #class = "form-control" })
#Html.ValidationMessageFor(model => model.DirectionIdSelected, "", new { #class = "text-danger" })
</div>
</div>
*#
</section>
}
</nav>
<div id="content" class="container">
<h2>Missions</h2>
#* #using (Html.BeginForm("Index", "Missions", FormMethod.Get))
{
#Html.TextBox("searching")
<input type="submit" value="submit" />
}
*#
<p class="newmission">
<input type="button" class="btn btn-info" value="Nouvelle Mission" onclick="location.href='#Url.Action("Create", "Missions")'" />
</p>
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.ActionLink("Pays", "Index",
new { SortOrder = Model.SortCountry})
</th>
<th class="col-md-1">
#Html.ActionLink("Date", "Index",
new { SortOrder = ViewBag.ListorderDate,
/*SelectedDesk = ViewBag.ListorderPays,
SelectedProgramme = ViewBag.ListorderDate,*/
})
</th>
<th class="col-md-2">
Personne
</th>
<th class="col-md-10">
Missions
</th>
<th class="col-md-10">
</th>
</tr>
#foreach (var item in Model.OnePageOfMissions)
{
<tr>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.decision)
</td>
<td class="col-md-2">
#Html.DisplayFor(modelItem => item.organization_hi_country.name_en)
</td>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.asked_date)
</td>
<td class="col-md-2"></td>
<td class="col-md-10">
<span class="typemission">Mission</span> #Html.DisplayFor(modelItem => item.list_type.name_en, new { #class = "typemission" }) : #Html.DisplayFor(modelItem => item.list_nature.name_en, new { #class = "typemission" })
<div>
<!-- les boutons d'actions -->
details
</div>
<!-- le contenu masqué -->
<section id="#Html.DisplayFor(modelItem => item.id)" class="collapse">
<div class="well">
<p><em>Statut: </em>#Html.DisplayFor(modelItem => item.list_statut.name_en)</p>
<p><em>Durée: </em>#Html.DisplayFor(modelItem => item.duration) jours</p>
<p><em>Flexibilité: </em>#Html.DisplayFor(modelItem => item.list_flexibility.name_en) </p>
<p><em>Priorité: </em>#Html.DisplayFor(modelItem => item.list_priority.name_en) </p>
<p><em>Commentaires: </em>#Html.DisplayFor(modelItem => item.comments) </p>
</div>
</section>
</td>
<td class="col-md-10">
#Html.ActionLink("Edit", "Create", new { id = item.id })
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
#Html.PagedListPager((IPagedList)Model.OnePageOfMissions, page => Url.Action("Index", new { page, ProgrammeIdSelected = Model.ProgrammeIdSelected }))
</table>
I'm following this guide here to create a step wizard to traverse multiple pages with forms on each while saving each forms data to store in my db but the problem I'm having is on the second page 'addressDetails'. When I press the prevBtn to return to the previous page 'basicDetails', my form is trying to do client side validation and I get all the validation errors instead of posting to my action method to see whether the prevBtn or nextBtn was pressed
Here is my addressDetails page
<div class="col-sm-7 col-sm-offset-1">
#using (Html.BeginForm("AddressDetails", "User", FormMethod.Post)) {
<div class="row">
<h3>What's the address for this payout method?</h3>
</div>
<div class="row">
<div class="form-group">
<label for="AddressLine1">Street address</label>
#Html.TextBoxFor(m => m.StreetAddressLine1, new { #id = "AddressLine1", #class = "form-control input-lg", placeholder = "e.g. 123 Main St." }) #Html.ValidationMessageFor(m => m.StreetAddressLine1,
"", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group">
<label for="AddressLine2">Apt, suite, bldg. (optional)</label>
#Html.TextBoxFor(m => m.StreetAddressLine2, new { #id = "AddressLine2", #class = "form-control input-lg", placeholder = "e.g. Apt #6" }) #Html.ValidationMessageFor(m => m.StreetAddressLine2,
"", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-sm-6" style="padding-left: 0px; padding-right: 5px;">
<div class="form-group">
<label for="City">City</label> #Html.TextBoxFor(m => m.City, new { #id = "City", #class = "form-control input-lg" })
#Html.ValidationMessageFor(m => m.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6" style="padding-left: 5px; padding-right: 0px;">
<div class="form-group">
<label for="State">State / Province</label>
#Html.DropDownListFor(m => m.StateCode, new SelectList(Model.StateList, "Value", "Text"), "", new { #id = "State", #class = "btn-group-lg countryList form-control selectpicker" }) #Html.ValidationMessageFor(m
=> m.StateCode, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="PostalCode">Zip code / Postal code</label>
#Html.TextBoxFor(m => m.PostalCode, new { #id = "PostalCode", #class = "form-control input-lg", placeholder = "e.g. 94102" }) #Html.ValidationMessageFor(m => m.PostalCode, "", new { #class =
"text-danger" })
</div>
</div>
<div class="row">
#Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.CountryList, "Value", "Text"), new { #id = "Country", #class = "btn-group-lg countryList form-control selectpicker" })
</div>
<div class="row">
<hr />
</div>
<div class="row">
<div class="col-sm-12">
<input type="submit" name="prevBtn" value='Previous' />
<input type="submit" name="nextBtn" value='Next' />
</div>
</div>
}
</div>
Here is my action method
[HttpPost]
public ActionResult AddressDetails(UserAddressViewModel addressViewModel, string prevBtn, string nextBtn)
{
YogaProfileBankAccount obj = GetBankAccount();
if (prevBtn != null)
{
UserBillingViewModel billingViewModel = new UserBillingViewModel();
//bd.CustomerID = obj.CustomerID;
//bd.CompanyName = obj.CompanyName;
return View("BasicDetails", billingViewModel);
}
if (nextBtn != null)
{
if (ModelState.IsValid)
{
//obj.Address = data.Address;
//obj.City = data.City;
//obj.Country = data.Country;
//obj.PostalCode = data.PostalCode;
return View("AccountDetails");
}
}
return View();
}
So here is what happens when I press previous, all the fields try to get validated
I am making my MVC application. My view PickGroupForHomework is redirected to by
return RedirectToAction("PickGroupForHomework", "Account", new { subject_id = id, qty=model.qty });
Of course subject_id and qty are parameters of PickGroupForHomeworkViewModel. The controller looks like this:
public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model)
{
ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
model.groups = entities.Groups.ToList();
model.users = entities.Users.ToList();
int id = model.subject_id;
var subj = entities.Subjects
.Where(b => b.class_id == model.subject_id)
.FirstOrDefault();
if (subj != null)
{
model.subject_name = subj.name;
}
if (ModelState.IsValid)
{
DateTime myDate = DateTime.ParseExact(model.deadline+ " "+model.time, "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
ClassDeclarationsDBEntities2 entities2 = new ClassDeclarationsDBEntities2();
int total = entities2.Tasks.Count();
for (int i=0;i<model.task_names.Count;i++)
{
ClassDeclarationsDBEntities2 entities3 = new ClassDeclarationsDBEntities2();
int maxid;
if (total == 0)
{
maxid = 0;
}
else {
maxid = entities3.Tasks.Max(u => u.task_id);
}
var task = new Models.Task(model.task_names[i], model.subject_id, myDate, model.points[i], maxid + 1);
entities3.Tasks.Add(task);
entities3.SaveChangesAsync();
}
return RedirectToAction("OperationSuccess", "Account");
}
else
{
return View(model);
}
return View(model);
}
At first, everything loads correctly with correct URL including data passed from previous view. The form I am displaying now includes validation. If a user makes mistake in form, which indicades ModelState.IsValid=false, the window is reloaded. But I do not know why it is reloaded without data passed from previous window: subject_id and qty. What am I doing wrong?
EDIT:
View: #model ClassDeclarationsThsesis.Models.PickGroupForHomeworkViewModel
#{
ViewBag.Title = "Pick Group For Homework"; }
<h2>Setting homework for #Model.subject_name</h2>
#foreach (var user in Model.users) {
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 2.ToString()|| user.user_type.Replace(" ", String.Empty) == 3.ToString())
{
using (Html.BeginForm("PickGroupForHomework", "Account", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
<hr />
<div class="form-group">
#Html.LabelFor(model => model.deadline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.deadline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.deadline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.time, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.time, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.deadline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.file, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<div class="editor-field">
<input type="file" name="file" />
</div>
</div>
</div>
<div class="form-group">
<table>
<tr>
<th>
Name of task
</th>
<th>
Points
</th>
</tr>
#for (int i = 0; i < Model.qty; i++)
{
<tr>
<th>
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.task_names[i], new { #class = "form-control" })
</div>
</div>
</th>
<th>
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.points[i], new { #class = "form-control" })
</div>
</div>
</th>
</tr>
}
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString() )
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
Your problem is subject_id is not in your form, so when you post back the form it sends 0 value to the server.
you need to add a field inside form , you can add a Text or hidden field
#Html.HiddenFor(m => m.subject_id)
I have an Index page with various filtering options on it, all included within a PagedList. They all appear to be working fine, except for the dates.
When I first filter by date, they work fine however when I click on a page number at the bottom, the search criteria for my date is disappearing.
I can see that I can passing the search term in the paged list, and I can see this date hit my controller and the filtering happen but the ViewBag.filterStartDate and ViewBag.filterEndDate just aren't binding back to my textboxes for some reason.
Index.cshtml:
#using PagedList.Mvc
#model PagedList.IPagedList<Job>
#using (Html.BeginForm("Index", "Jobs", FormMethod.Get, new { #class = "form-inline", role = "form" }))
{
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Filter Search Results</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">
#Html.Label("By Id: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterId", ViewBag.filterId as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Address Line 1: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterAddress1", ViewBag.filterAddress1 as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Username: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterUsername", ViewBag.filterUsername as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Contract: ", new { #class = "col-md-4 control-label" })
#Html.DropDownList("filterContract", null, "-- Select One --",
new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("Date Created Start: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterStartDate", ViewBag.filterStartDate as string, new { #class = "form-control date", type = "date" })
</li>
<li class="list-group-item">
#Html.Label("Date Created End: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterFinishDate", ViewBag.filterFinishDate as string, new { #class = "form-control date", type = "date" })
</li>
<li class="list-group-item">
#Html.Label("By App: ", new { #class = "col-md-4 control-label" })
#Html.DropDownList("filterApp", null, "-- Select One --",
new { #class = "form-control" })
</li>
</ul>
<input type="submit" value="Apply Filter" class="btn btn-default" />
</div>
<div id="items" style="padding: 15px;">
#Html.Partial("Jobs", Model)
</div>
</div>
}
Jobs.cshtml:
#using System.Web.UI.WebControls
#using PagedList.Mvc
#model PagedList.IPagedList<Job>
#Html.ActionLink("Create New", "Create", null, new { #style = "float: left" })
#Html.ActionLink("Import Jobs", "Import", null, new { #style = "padding-left: 15px" })
#Html.ValidationSummary(true)
<table class="table">
<tr>
<th class="mobileview">
#Html.DisplayName("JobId")
</th>
<th>
#Html.DisplayName("Description")
</th>
<th class="mobileview">
#Html.DisplayName("Address")
</th>
<th class="mobileview">
#Html.DisplayName("Priority")
</th>
<th>
#Html.DisplayName("Date Created")
</th>
<th>
#Html.DisplayName("Username")
</th>
</tr>
#foreach (var item in Model)
{
<tr class="formrow">
<td class="mobileview">
#Html.DisplayFor(modelItem => item.JobId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td class="mobileview">
#Html.DisplayFor(modelItem => item.Address1)
</td>
<td class="mobileview">
#Html.DisplayFor(modelItem => item.Priority)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.UserName)
</td>
<td class="mobileview">
#Html.ActionLink("View Job", "Details", new { id = item.JobId })
</td>
<td class="mobileview">
#if (item.Data != null)
{
#Html.ActionLink("View Data", "Details", "AppForms", new { id = item.Data.Id }, null)
}
else
{
#Html.DisplayFor(modelItem => item.Status)
}
</td>
</tr>
}
</table>
<p>Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount</p>
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, filterAddress1 = ViewBag.filterAddress1, filterId = ViewBag.filterId, filterUsername = ViewBag.filterUsername, filterStartDate = ViewBag.filterStartDate, filterFinishDate = ViewBag.filterFinishDate, filterApp = ViewBag.selectedApp, filterContract = ViewBag.selectedContract }), PagedListRenderOptions.Classic)
JobsController.cs:
public ActionResult Index(string sortOrder, string currentFilter, string filterId, string filterAddress1, int? page, String filterApp, String filterContract, DateTime? filterStartDate, DateTime? filterFinishDate, String filterUsername)
{
//...Other filtering
//Filter by date
if (filterStartDate != null)
{
jobs = jobs.Where(x => x.DateCreated >= filterStartDate);
//ViewBag.filterStartDate = filterStartDate.Value.Year + "-" + filterStartDate.Value.Month + "-" + filterStartDate.Value.Day;
ViewBag.filterStartDate = filterStartDate;
}
if (filterFinishDate != null)
{
//Make sure we're checking to the end of the end date (ie 01/01/2015 23:59:59)
filterFinishDate = filterFinishDate.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
jobs = jobs.Where(x => x.DateCreated <= filterFinishDate);
//ViewBag.filterFinishDate = filterFinishDate.Value.Year + "-" + filterFinishDate.Value.Month + "-" + filterFinishDate.Value.Day;
ViewBag.filterFinishDate = filterFinishDate;
}
int pageSize = int.Parse(ConfigurationManager.AppSettings["MaxPageItemCount"]);
int pageNumber = page ?? 1;
return this.View(jobs.ToPagedList(pageNumber, pageSize));
}
#Html.TextBox() can pull values out of the ModelState or ViewData.
Try building the html for the date input manually like this:
<input type="date" name="filterStartDate" id="filterStartDate" class="form-control date" value="#ViewBag.filterStartDate.ToString("yyyy-MM-dd")"/>
Resolved the issue by manually creating the date inputs rather tahn relying on Razor to do it for me!
#if (ViewBag.filterStartDate != null)
{
<input type="date" name="filterStartDate" id="filterStartDate" value="#ViewBag.filterStartDate.ToString("yyyy-MM-dd")" />
}
else
{
<input type="date" name="filterStartDate" id="filterStartDate" value="" />
}