MVC view data passing - c#

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)

Related

Change what submit button does based on editorFor circumstance

I have an edit form page on my website that allows users to edit quantities, on this page I used editorFor's which look like this
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { min = 0, #class = "form-control" } })
And I have a submit button that looks like this
<input type="submit" value="Save" class="btn" />
I want to make it so that if the user increases the qty, it will go ahead and run the post method. But on the other hand, if a user was to decrease the qty, I would want the save button to look like this
<input type="submit" value="Save" onclick="confirm()" class="btn" />
Where it gets the user to confirm before running the post.
How can I make my save button change based on what the user types into the editorFor?
Here is my entire view page as requested
#model PIC_Program_1._0.Models.JODetails
#using PIC_Program_1._0.Models
#{
ViewBag.Title = "Edit";
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == Model.ID);
Component comp = db.Components.Find(Model.ComponentID);
Item i = db.Items.Find(Model.ItemID);
}
<script type="text/javascript">
function clicked(e) {
if(#i != null ) {
var itemDiff = // model - new editorfor value;
if (!confirm('Are you sure? Doing this will reduce item ' + #i.ItemID + ' future stock to ' + itemDiff))e.preventDefault();
}
}
function OnChangeEvent(){
alert("value is changed");
var itemQty = $('#itemQTY').val();
if (itemQty < #Model.item_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
</script>
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JODetails</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.subDetail)
<p style="color:red">#ViewBag.Error</p>
<div class="form-group">
#Html.LabelFor(model => model.ItemID, "ItemID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ItemID", null, "-- Select --", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.item_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.item_qty, new { disabled = "disabled", #Value = Model.item_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent()", min = 0, #class = "form-control" #id = "itemQTY"} })
#Html.ValidationMessageFor(model => model.item_qty, "", new { #class = "text-danger" })
}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn"/>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
For the on change you can on your editor for:
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id ="someId" } })
<script type="text/javascript">
function OnChangeEvent(){
var itemQty = $('#someID').val(); //This will give you value of editor for
alert("new value is: " + itemQty);
//Call some controller function here and do your increase/decrease logic and return value so we know what to do. also perform your save in controller too if needed.
#Model.IsChanged = true;
//do other functions here also like change button
//if decrease add below
btn.Attributes.Add("onclick", "confirm()");
//if increase remove and perform save.
}
</script>
You can also change the button from that method. There is no good way to do on call events at a server level, unless using blazor, so javascript is your best bet here.
Updated answer per OP:
#model PIC_Program_1._0.Models.JODetails
#using PIC_Program_1._0.Models
#{
ViewBag.Title = "Edit";
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == Model.ID);
Component comp = db.Components.Find(Model.ComponentID);
Item i = db.Items.Find(Model.ItemID);
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JODetails</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.subDetail)
<p style="color:red">#ViewBag.Error</p>
<div class="form-group">
#Html.LabelFor(model => model.ItemID, "ItemID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ItemID", null, "-- Select --", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.item_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.item_qty, new { disabled = "disabled", #Value = Model.item_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "itemQTY"} })
#Html.ValidationMessageFor(model => model.item_qty, "", new { #class = "text-danger" })
}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn"/>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
function OnChangeEvent(){
alert("value is changed");
var itemQty = $('#itemQTY').val();
if (itemQty < #Model.item_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
</script>

Dynamic Add and Edit of Data in Asp.net Mvc using Razor view

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. :)

How to use pagedlist with post method

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>

Step wizard in Asp.Net MVC unintentionally validating with prev button

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

How to set Input field to READONLY using Javascript based on the current month

THEAPP:
ASP.NET MVC 5 Application
TABLE:
[Id , Employer, ITONumber, Description, TECNumber, TECVersion, Level, Credits, Duration, Sector, Status, Approval, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
REQUIRMENT:
Set the the Months field to be edited based on the current Month using Javascript
for instance: Current month is [Apr] then only all the fields in the TABLE should be set to READONLY on the Edit Page/form. EXCEPT for the [Apr]
_layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#*#Scripts.Render("~/bundles/modernizr")*#
<script type="text/javascript" src="ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Pipeline Data", "Index", "Home", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
<li>#Html.ActionLink("Pipeline", "Index", "Pipeline")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Edit.cshtml
#model PipelineApp.Models.Pipelinedata
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Pipelinedata</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Employer, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Employer)*#
#Html.TextBoxFor(model => model.Employer, new { #readonly = "true" })
#Html.ValidationMessageFor(model => model.Employer)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ITONumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.ITONumber)*#
#Html.TextBoxFor(model => model.ITONumber, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.ITONumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Description)*#
#Html.TextBoxFor(model => model.Description, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TECNumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.TECNumber)*#
#Html.TextBoxFor(model => model.TECNumber, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.TECNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TECVersion, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.TECVersion)*#
#Html.TextBoxFor(model => model.TECVersion, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.TECVersion)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Level, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Level)*#
#Html.TextBoxFor(model => model.Level, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Level)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Credits, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Credits)*#
#Html.TextBoxFor(model => model.Credits, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Credits)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Duration, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Duration)*#
#Html.TextBoxFor(model => model.Duration, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Duration)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sector, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Sector)*#
#Html.TextBoxFor(model => model.Sector)
#Html.ValidationMessageFor(model => model.Sector)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Status, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Status)*#
#Html.TextBoxFor(model => model.Status, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Status)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Approval, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Approval)*#
#Html.TextBoxFor(model => model.Approval, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Approval)
</div>
</div>
<script type="text/javascript">
//alert("test")
$("document").ready(function () {
var today = new Date();
var month = today.getMonth() + 1;
$('.month').each(function () {
if ($(this).attr('id') == month) {
$(this).attr("disabled", false);
//$(this).removeAttr('readonly');
} else {
$(this).attr("disabled", true);
//$(this).attr('readonly', 'readonly');
}
});
});
</script>
<div id="" class="form-group">
#Html.LabelFor(model => model.Jan, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Jan)*#
#Html.TextBoxFor(model => model.Jan, new { id = "1", #class = "month" })
#Html.ValidationMessageFor(model => model.Jan)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Feb, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Feb)*#
#Html.TextBoxFor(model => model.Feb, new { id = "2", #class = "month" })
#Html.ValidationMessageFor(model => model.Feb)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Mar, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Mar)*#
#Html.TextBoxFor(model => model.Mar, new { id = "3", #class = "month" })
#Html.ValidationMessageFor(model => model.Mar)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Apr, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Apr)*#
#Html.TextBoxFor(model => model.Apr, new { id = "4", #class = "month" })
#Html.ValidationMessageFor(model => model.Apr)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.May, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.May)*#
#Html.TextBoxFor(model => model.May, new { id = "5", #class = "month" })
#Html.ValidationMessageFor(model => model.May)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Jun, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Jun)*#
#Html.TextBoxFor(model => model.Jun, new { id = "6", #class = "month" })
#Html.ValidationMessageFor(model => model.Jun)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Jul, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Jul)*#
#Html.TextBoxFor(model => model.Jul, new { id = "7", #class = "month" })
#Html.ValidationMessageFor(model => model.Jul)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Aug, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Aug)*#
#Html.TextBoxFor(model => model.Aug, new { id = "8", #class = "month" })
#Html.ValidationMessageFor(model => model.Aug)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Sep, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Sep)*#
#Html.TextBoxFor(model => model.Sep, new { id = "9", #class = "month" })
#Html.ValidationMessageFor(model => model.Sep)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Oct, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Oct)*#
#Html.TextBoxFor(model => model.Oct, new { id = "10", #class = "month" })
#Html.ValidationMessageFor(model => model.Oct)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Nov, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Nov)*#
#Html.TextBoxFor(model => model.Nov, new { id = "11", #class = "month" })
#Html.ValidationMessageFor(model => model.Nov)
</div>
</div>
<div id="" class="form-group">
#Html.LabelFor(model => model.Dec, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Dec)*#
#Html.TextBoxFor(model => model.Dec, new { id = "12", #class = "month" })
#Html.ValidationMessageFor(model => model.Dec)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
PipelineController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PipelineApp.Models;
namespace PipelineApp.Controllers
{
public class PipelineController : Controller
{
private PipelineEntities db = new PipelineEntities();
//CUSTOM GET: /Pipelinedata/ Sector Filtering/ Sort Order
public ActionResult Index(string sector, string sortOrder, int? page)
{
//Filter Secors ------------------------------
ViewBag.Sector = (from r in db.Pipelinedatas
select r.Sector).Distinct();
//---------------------------------------------
var model = from r in db.Pipelinedatas
where r.Sector == sector || sector == null || sector == ""
select r;
//Sort Order ----------------------------------
ViewBag.CurrentSort = sortOrder; //Paging
ViewBag.EmployerSortParm = String.IsNullOrEmpty(sortOrder) ? "emp_name" : "";
ViewBag.ITOSortParm = String.IsNullOrEmpty(sortOrder) ? "ITO" : "";
ViewBag.JanSortParm = String.IsNullOrEmpty(sortOrder) ? "January" : "";
ViewBag.FebSortParm = String.IsNullOrEmpty(sortOrder) ? "February" : "";
ViewBag.MarSortParm = String.IsNullOrEmpty(sortOrder) ? "March" : "";
ViewBag.AprSortParm = String.IsNullOrEmpty(sortOrder) ? "April" : "";
ViewBag.MaySortParm = String.IsNullOrEmpty(sortOrder) ? "May" : "";
ViewBag.JunSortParm = String.IsNullOrEmpty(sortOrder) ? "June" : "";
ViewBag.JulSortParm = String.IsNullOrEmpty(sortOrder) ? "July" : "";
ViewBag.AugSortParm = String.IsNullOrEmpty(sortOrder) ? "August" : "";
ViewBag.SepSortParm = String.IsNullOrEmpty(sortOrder) ? "September" : "";
ViewBag.OctSortParm = String.IsNullOrEmpty(sortOrder) ? "October" : "";
ViewBag.NovSortParm = String.IsNullOrEmpty(sortOrder) ? "November" : "";
ViewBag.DecSortParm = String.IsNullOrEmpty(sortOrder) ? "December" : "";
ViewBag.SectorSortParm = sortOrder == "sec" ? "ITO" : "sec";
switch (sortOrder)
{
case "emp_name":
model = model.OrderByDescending(s => s.Employer);
break;
case "sec":
model = model.OrderBy(s => s.Sector);
break;
case "ITO":
model = model.OrderByDescending(s => s.ITONumber);
break;
case "January":
model = model.OrderByDescending(s => s.Jan);
break;
case "February":
model = model.OrderByDescending(s => s.Feb);
break;
case "March":
model = model.OrderByDescending(s => s.Mar);
break;
case "April":
model = model.OrderByDescending(s => s.Apr);
break;
case "May":
model = model.OrderByDescending(s => s.May);
break;
case "June":
model = model.OrderByDescending(s => s.Jun);
break;
case "July":
model = model.OrderByDescending(s => s.Jul);
break;
case "August":
model = model.OrderByDescending(s => s.Aug);
break;
case "September":
model = model.OrderByDescending(s => s.Sep);
break;
case "October":
model = model.OrderByDescending(s => s.Oct);
break;
case "November":
model = model.OrderByDescending(s => s.Nov);
break;
case "December":
model = model.OrderByDescending(s => s.Dec);
break;
default:
model = model.OrderBy(s => s.Id);
break;
}
//---------------------------------------------
//Paging --------------------------------------
//int pageSize = 3;
//int pageNumber = (page ?? 1);
//return View(model.ToPagedList(pageNumber, pageSize));
//---------------------------------------------
return View(model);
}
// GET: /Pipeline/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// GET: /Pipeline/Create
public ActionResult Create()
{
return View();
}
// POST: /Pipeline/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Pipelinedatas.Add(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Entry(pipelinedata).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
db.Pipelinedatas.Remove(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
As I'm newbie, would be please to see some proper instructions on what should be done. As always your time is Appreciated
Here Is the fiddle CLICK
give id to all of your months
like january 1,february 2... December 12
Sample
For january #Html.EditorFor(model => model.Jan,null,new {id="1",#class="month"})
For November
#Html.EditorFor(model => model.Nov,null,new {id="11",#class="month"})
then in your javascript add below.This is the most easiest way to do it
$(document).ready(function() {
var today=new Date();
var month=today.getMonth()+1;
$('.month').each(function(){
if($(this).attr('id')==month)
{
$(this).attr("disabled",false);
}
else
{$(this).attr("disabled",true);
}
});
});
If you are using jquery 1.5 or 1.5- then instead of using attr use prop.but if you are using jquery 1.6+ then the answer should work for you.
Try this:
View:
<div id="" class="form-group">
#Html.LabelFor(model => model.Jan, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.TextBoxFor(model => model.Jan)*#
#Html.TextBoxFor(model => model.Jan, new { id = "1", #class = "month", #onload = "checkDate()" })
#Html.ValidationMessageFor(model => model.Jan)
</div>
</div>
Javascript:
function checkDate(){
var today=new Date();
var month=today.getMonth()+1;
$('.month').each(function(){
if($(this).attr('id')==month)
{
$(this).prop("disabled",false);
}
else
{
$(this).prop("disabled",true);
}
}

Categories

Resources