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

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

Related

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

Deleting and Adding rows as an edit function in visual studio

The problem is when i want to edit a song in my project which has 4 genres and let's say i want to remove 1 and save, it drops an exception. My idea was to tell the controller to remove the 4 i had on the song and add the 3 which i chose. But that would mean removing from the local database and adding the new ones, i just have no idea how to do it. Any help is appreciated.
I made a pivot DataTable which contains song and genre ID's and which is conected to 2 other DataTables, where one has the genre types and the other song information. The listBoxFor in the view shows which genres are in the song, but when i delete one it doesn't save. I think the change needs to happen within the HttpPost of the Edit controller.
I am still new to coding and programming so I apologize if my question isn't too precise. If any more information is needed please tell me.
This is the Controller:
using (ApplicationDbContext db = new ApplicationDbContext())
{
var song = db.Songs.Find(model.SongId);
int[] genreIds = db.SongsGenres.Where(x => x.SongId == song.Id).Select(x=> x.GenreId).ToArray();
song.Performer = model.Performer;
song.Title = model.Title;
//song.Id = model.GenreIds;
song.Year = model.Year;
song.YoutubeLink = model.YoutubeLink;
db.Entry(song).State = EntityState.Modified;
foreach (var genreId in model.GenreIds)
{
// tu treba ici if petlja koja izbriše stari zapis iz baze
// i stavi novi editirani
db.SongsGenres.Add(new SongsGenre
{
Song = song,
//SongId = song.Id,
GenreId = genreId
});
}
db.SaveChanges();
return RedirectToAction("List");
}
}
}
}
This is the HTML(view):
#using System.Web.UI.WebControls
#model MusicBox.Models.EditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Editiraj pjesmu</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="Performer">Izvođač</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Performer, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Performer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Title">Pjesma</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Year">Godina</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Year, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Year, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="YoutubeLink">Youtube link</label>
<div class="col-md-10">
#Html.EditorFor(model => model.YoutubeLink, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.YoutubeLink, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Genre">Žanr</label>
<div class="col-md-10">
#Html.ListBoxFor(model => model.GenreIds, new SelectList(Model.Genres, "Value", "Text"), htmlAttributes: new { #class = "form-control select2", required = "required", multiple = "multiple" })
#*#Html.EditorFor(model => model.GenreIds, new {htmlAttributes = new {#class = "form-control"}})*#
#Html.ValidationMessageFor(model => model.GenreIds, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(model => model.SongId)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spremi" class="btn btn-primary" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#Html.ActionLink("Back to List", "List")
</div>
</div>
}
#section scripts
{
<script type="text/javascript">
$(".select2").select2({
val: '#Html.Raw(Json.Encode(Model.GenreIds))'
});
</script>
}
EDITED.

populate drop down list according to choice in previous drop down list

I am a new developer and I am trying to populate a drop down list as the result of what was chosen in a previous drop down list. I am stuck and would appreciate a full answer, I think I need a script somewhere but am not sure where to put it, and where to include the script tag.
Controller:
//// GET: TmplRisks/Create
public ActionResult Create()
{
ViewBag.TRisks = db.TmplRisks.ToList();
ViewBag.CategoryL1 = new SelectList(db.CatRiskLevel1Categories, "RiskLevel1CategoryID", "Level1");
//ViewBag.CategoryL2 = new SelectList(db.CatRiskLevel2Categories, "RiskLevel2CategoryID", "Level2");
var model = new TmplRisk();
return View(model);
}
// POST: TmplRisks/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 = "TRiskID,Name,Description,Source,IsKeyRisk,CategoryL1,CategoryL2,Active")] TmplRisk model)
{
if (ModelState.IsValid)
{
db.TmplRisks.Add(model);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.TRisks = db.TmplRisks.ToList();
ViewBag.CategoryL1 = new SelectList(db.CatRiskLevel1Categories, "RiskLevel1CategoryID", "Level1", model.CategoryL1);
//ViewBag.CategoryL2 = new SelectList(db.CatRiskLevel2Categories, "RiskLevel2CategoryID", "Level2", tmplRisk.CategoryL2);
return View(model);
}
public ActionResult FillCategoryLevel2(int category1)
{
var categoryLevel2 = db.CatRiskLevel2Categories.Where(c => c.CatRL1ID == category1);
return Json(categoryLevel2, JsonRequestBehavior.AllowGet);
}
where do i call my FillCategoryLevel2() from?
View:
#model RiAct._02.Models.TmplRisk
#{
ViewBag.Title = "Create";
}
<head>
<script type="text/javascript" src="~/Scripts/FillCategoryLevel2.js"></script>
</head>
<div class="container col-md-12">
<div class="row">
#Html.Partial("List", (IEnumerable<RiAct._02.Models.TmplRisk>)ViewBag.TRisks)
#using (Html.BeginForm())
{
<script>
function FillCategoryLevel2() {
var category1Id = $('#CategoryL1').val();
$.ajax({
url: '/TmplRisks/Create',
type: "GET",
dataType: "JSON",
data: { CategoryL1: category1Id },
success: function (categoryL2) {
$("#CategoryL2").html(""); // clear before appending new list
$.each(categoryL2, function (i, CategoryL2) {
$("#CategoryL2").append(
$('<option></option>').val(CategoryL2.RiskLevel2CategoryID).html(CategoryL2.Level2));
});
}
});
}
</script>
#Html.AntiForgeryToken()
<div class="col-md-6">
<div class="panel panel-default list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<div class="panel-title list-panel-title">
New Risk Template
</div>
</div>
<div class="panel-body">
<div class="form-horizontal text-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group col-md-offset-1">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-offset-1">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-offset-1">
#Html.LabelFor(model => model.Source, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.EditorFor(model => model.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.CategoryL1, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownList("CategoryL1", null, "Select One", htmlAttributes: new { #class = "form-control", #onchange = "FillCategoryLevel2()" })
#Html.ValidationMessageFor(m => m.CategoryL1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.CategoryL2, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(m => m.CategoryL2,
new SelectList(Enumerable.Empty<SelectListItem>(), "RislLevel2CategoryID", "Level2"),
"Select one",
new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.CategoryL2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsKeyRisk, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9 text-left">
#Html.EditorFor(model => model.IsKeyRisk)
#Html.ValidationMessageFor(model => model.IsKeyRisk, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9 text-left">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="btn-group pull-right">
#Html.ActionLink("Reset", "Create", null, new { #class = "btn btn-default" })
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

attributes not working for model ASP.NET MVC 5

I have This Model in my web application:
namespace BoardMeeting.Models
{
public class ChangePassModel
{
[Required(ErrorMessage = "password must be entered")]
[DataType(DataType.Password)]
public string Password { get; set; }
public string Username { get; set; }
[Required(ErrorMessage = "you must enter the new password")]
[DataType(DataType.Password)]
public string NewPass { set; get; }
[DataType(DataType.Password)]
[Compare("NewPass", ErrorMessage = "The Passwords Do not match")]
public string ConfimedPass { set; get; }
}
}
And Here is my View:
#model BoardMeeting.Models.ChangePassModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<div class="form-group ">
<div class="row" dir="rtl">
<div>
#Html.Label("username :", new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.LabelFor(m => m.Username, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.Label("user :", new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.LabelFor(m => m.Username, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
</div>
</div>
<div class="form-group">
<div class="row" dir="rtl">
<div>
#Html.Label("old password", new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.TextBoxFor(m=>m.Password, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right form-control", style = "margin-top:5px;" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="row" dir="rtl">
<div>
#Html.Label("new password", new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.TextBoxFor(m => m.NewPass, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right form-control", style = "margin-top:5px;" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="row" dir="rtl" style="align-content:center">
<div>
#Html.Label("confirm new password", new { #class = "col-xs-12 col-md-4 col-sm-3 col-lg-2 pull-right", style = "margin-top:5px;" })
</div>
<div>
#Html.TextBoxFor(m => m.ConfimedPass, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right form-control", style = "margin-top:5px;",type="password" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="submit" class="btn btn-success pull-right" />
</div>
</div>
}
The Problem is none of the Attributes of The Model are working.I have Checked the following Options:
1-I have this values in my web.config file under the appsettings:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
2-I have checked the ModelState.IsValid in my controller.
It is strange that i have a similar code for my login and it has no problem.
And I should say That I am new to ASP.NET MVC and I don't Know If There is Anything else i should do. Do You have Any Suggestions for this problem?
Ok there are a few things wrong here.
You are using an overload which will set your error message to be a blank string.
Notice the second parameter below.
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
Simply replace the blank string with a null and it will pull it from the attributes instead:
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "text-danger" })
Also you have copied and pasted the same code per property underneath but kept the Password as the first parameter:
#Html.TextBoxFor(m => m.NewPass, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right form-control", style = "margin-top:5px;" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
You will need to change them to match the controls above and also replace the blank string:
#Html.TextBoxFor(m => m.NewPass, new { #class = "col-xs-12 col-md-2 col-sm-3 col-lg-2 pull-right form-control", style = "margin-top:5px;" })
#Html.ValidationMessageFor(m => m.NewPass, null, new { #class = "text-danger" })
This will need to be done for all of the properties within your view.

asp.net MVC Validation Returning new View with validation

When I click my 'continue' button my form generates a new view of the fields being validated and shows whats missing. How do I get the validations to show on the same partialview.
My controller:
namespace LoanApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// This is how we prepopulate the list of loan types. Doing it here b/c one day this will be from a list from a service.
var vm = new Step1ViewModel();
vm.AllAvailableLoanTypes = new List<string>();
vm.AllAvailableLoanTypes.Add("Auto Refinance");
vm.AllAvailableLoanTypes.Add("Auto Purchase");
vm.AllAvailableLoanTypes.Add("Auto PreApproval");
vm.AllAvailableLoanTypes.Add("Signature Loan");
vm.AllAvailableLoanTypes.Add("Credit Card");
vm.AllAvailableLoanTypes.Add("Home Equity");
vm.AllAvailableLoanTypes.Add("10 Year 1st Mortgage");
return View(vm);
}
[HttpPost]
public ActionResult SelectLoanType(Step1ViewModel model)
{
// For this example I slapped the type in Session, you could post it through in each subsequent viewmodel and just hide it on the form in a Html.Hidden()
Session["LoanType"] = model.LoanType;
return PartialView("PrimaryApplicantPartial");
}
[HttpPost]
public ActionResult PrimaryApplicant(PrimaryApplicantViewModel model)
{
// Make sure session didnt get eaten.
var loanType = "";
if (Session["LoanType"] != null)
{
loanType = Session["LoanType"].ToString();
}
// Here we decide which view to show next. in the frotn end you may need to handle what to change labels to in the wizard maybe via JQ/JS
switch (loanType)
{
case "Auto Refinance":
if (ModelState.IsValid)
{
return PartialView("AutoRefinance");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "Auto Purchase":
if (ModelState.IsValid)
{
return PartialView("AutoPurchase");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "Auto PreApproval":
if (ModelState.IsValid)
{
return PartialView("AutoPreApproval");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "Signature Loan":
if (ModelState.IsValid)
{
return PartialView("SignatureLoan");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "Credit Card":
if (ModelState.IsValid)
{
return PartialView("CreditCard");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "Home Equity":
if (ModelState.IsValid)
{
return PartialView("HomeEquity");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
case "10 Year 1st Mortgage":
if (ModelState.IsValid)
{
return PartialView("TenYearFirstMortgage");
}
else
{
ModelState.AddModelError("", "Information Incomplete");
return PartialView("PrimaryApplicantPartial");
}
default:
return PartialView("PrimaryApplicantPartial");
}
}
[HttpPost]
public ActionResult AutoRefinance(AutoRefinanceViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("AutoRefinanceFinal");
}
[HttpPost]
public ActionResult AutoPurchase(AutoPurchaseViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
[HttpPost]
public ActionResult AutoPreApproval(AutoPreApprovalViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
[HttpPost]
public ActionResult SignatureLoan(SignatureLoanViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
[HttpPost]
public ActionResult CreditCard(CreditCardViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
[HttpPost]
public ActionResult HomeEquity(HomeEquityViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
[HttpPost]
public ActionResult TenYearFirstMortgage(TenYearFirstMortgageViewModel model)
{
//do stuff here
// This will fail for now with a lovely 500
return PartialView("NextView");
}
}
}
You will see the validation code above. And this is my partialview:
#using Newtonsoft.Json
#model LoanApp.Models.PrimaryApplicantViewModel
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.maskedinput.js"></script>
<script>
$("input[name='JointOwner']").change(function () {
$("#JointApplicantInfo").toggle();
});
jQuery(function ($) {
$("#dob").mask("99/99/9999");
$("#phone").mask("(999) 999-9999");
$("#ssn").mask("999-99-9999");
$("#zip").mask("99999");
});
</script>
#using (Ajax.BeginForm("PrimaryApplicant", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "step3", OnSuccess = "showStep3" }))
{
<h4>Primary Applicant Information</h4>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<hr/>
<div class="form-group">
#Html.LabelFor(m => m.FirstName, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control", placeholder = "First Name" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.MiddleName, new { #class = "form-control", placeholder = "Middle Name" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control", placeholder = "Last Name" })
</div>
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.SSN, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.SSN, new { #class = "form-control", placeholder = "Social Security Number", id = "ssn" })
#Html.ValidationMessageFor(m => m.SSN)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.DOB, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.DOB, new { #class = "form-control", placeholder = "Date of Birth", id = "dob" })
#Html.ValidationMessageFor(m => m.DOB)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", type = "email", placeholder = "Email Address" })
</div>
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.PhoneNumber, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control", placeholder = "Phone Number", id = "phone" })
</div>
#Html.ValidationMessageFor(m => m.PhoneNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Address1, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.Address1, new { #class = "form-control", placeholder = "Address 1" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.Address2, new { #class = "form-control", placeholder = "Address 2" })
</div>
#Html.ValidationMessageFor(m => m.Address1)
</div>
</div>
<div class="form-group">
<div class="col-md-3"></div>
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.City, new { #class = "form-control", placeholder = "City" })
#Html.ValidationMessageFor(m => m.City)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.State, new { #class = "form-control", placeholder = "State" })
#Html.ValidationMessageFor(m => m.State)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.Zip, new { #class = "form-control", placeholder = "Zip Code", id = "zip" })
#Html.ValidationMessageFor(m => m.Zip)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.HousingPayment, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.HousingPayment, new { #class = "form-control", placeholder = "Housing Payment" })
#Html.ValidationMessageFor(m => m.HousingPayment)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.HousingType, new { #class = "form-control", placeholder = "Housing Type" })
#Html.ValidationMessageFor(m => m.HousingType)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EmploymentType, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmploymentType, new { #class = "form-control", placeholder = "Employment Type" })
#Html.ValidationMessageFor(m => m.EmploymentType)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EmployerName, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmployerName, new { #class = "form-control", placeholder = "Employer Name" })
#Html.ValidationMessageFor(m => m.EmployerName)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EmploymentTitle, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmploymentTitle, new { #class = "form-control", placeholder = "Title" })
#Html.ValidationMessageFor(m => m.EmploymentTitle)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EmploymentStartDate, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmploymentStartDate, new { #class = "form-control", type = "date", placeholder = "Employment Start Date" })
#Html.ValidationMessageFor(m => m.EmploymentStartDate)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.MonthlyIncome, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.MonthlyIncome, new { #class = "form-control", placeholder = "Monthly Income" })
#Html.ValidationMessageFor(m => m.MonthlyIncome)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.AdditionalIncome, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.AdditionalIncome, new { #class = "form-control", placeholder = "Additional Income" })
#Html.ValidationMessageFor(m => m.AdditionalIncome)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.AdditionalIncomeSource, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.AdditionalIncomeSource, new { #class = "form-control", placeholder = "Additional Income Source" })
#Html.ValidationMessageFor(m => m.AdditionalIncomeSource)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.AdditionalIncomeAmt, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.AdditionalIncomeAmt, new { #class = "form-control", placeholder = "Additional Income Amount" })
#Html.ValidationMessageFor(m => m.AdditionalIncomeAmt)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointOwner, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value = "0" }, new { #checked = "" }) No</label>
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value = "1" }) Yes</label>
</div>
</div>
</div>
//Joint Applicant
<div id="JointApplicantInfo">
<h4>Joint Applicant Information</h4>
<div class="form-group">
#Html.LabelFor(m => m.JointFirstName, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointFirstName, new { #class = "form-control", placeholder = "First Name" })
#Html.ValidationMessageFor(m => m.JointFirstName)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointMiddleName, new { #class = "form-control", placeholder = "Middle Name" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointLastName, new { #class = "form-control", placeholder = "Last Name" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointSsn, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointSsn, new { #class = "form-control", placeholder = "Social Security Number", id = "ssm" })
#Html.ValidationMessageFor(m => m.JointSsn)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointDob, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointDob, new { #class = "form-control", placeholder = "Date of Birth", id = "dob" })
#Html.ValidationMessageFor(m => m.JointDob)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointEmail, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointEmail, new { #class = "form-control", type = "email", placeholder = "Email Address" })
</div>
#Html.ValidationMessageFor(m => m.JointEmail)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointPhoneNumber, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointPhoneNumber, new { #class = "form-control", placeholder = "Phone Number", id = "phone" })
</div>
#Html.ValidationMessageFor(m => m.JointPhoneNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointAddress1, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointAddress1, new { #class = "form-control", placeholder = "Address 1" })
#Html.ValidationMessageFor(m => m.JointAddress1)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointAddress2, new { #class = "form-control", placeholder = "Address 2" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-3"></div>
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointCity, new { #class = "form-control", placeholder = "City" })
#Html.ValidationMessageFor(m => m.JointCity)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointState, new { #class = "form-control", placeholder = "State" })
#Html.ValidationMessageFor(m => m.JointState)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointZip, new { #class = "form-control", placeholder = "Zip Code" })
#Html.ValidationMessageFor(m => m.JointZip)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointHousingPayment, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointHousingPayment, new { #class = "form-control", placeholder = "Housing Payment" })
#Html.ValidationMessageFor(m => m.JointHousingPayment)
</div>
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointHousingType, new { #class = "form-control", placeholder = "Housing Type" })
#Html.ValidationMessageFor(m => m.JointHousingType)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointEmploymentType, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointEmploymentType, new { #class = "form-control", placeholder = "Employment Type" })
#Html.ValidationMessageFor(m => m.JointEmploymentType)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointEmployerName, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointEmployerName, new { #class = "form-control", placeholder = "Employer Name" })
#Html.ValidationMessageFor(m => m.JointEmployerName)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointEmploymentTitle, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointEmploymentTitle, new { #class = "form-control", placeholder = "Title" })
#Html.ValidationMessageFor(m => m.JointEmploymentTitle)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointEmploymentStartDate, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointEmploymentStartDate, new { #class = "form-control", type = "date", placeholder = "Employment Start Date" })
#Html.ValidationMessageFor(m => m.JointEmploymentStartDate)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointMonthlyIncome, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointMonthlyIncome, new { #class = "form-control", placeholder = "Monthly Income" })
#Html.ValidationMessageFor(m => m.JointMonthlyIncome)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointAdditionalIncome, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointAdditionalIncome, new { #class = "form-control", placeholder = "Additional Income" })
#Html.ValidationMessageFor(m => m.JointAdditionalIncome)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointAdditionalIncomeSource, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointAdditionalIncomeSource, new { #class = "form-control", placeholder = "Additional Income Source" })
#Html.ValidationMessageFor(m => m.JointAdditionalIncomeSource)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.JointAdditionalIncomeAmt, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<div class="col-md-4">
#Html.TextBoxFor(m => m.JointAdditionalIncomeAmt, new { #class = "form-control", placeholder = "Additional Income Amount" })
#Html.ValidationMessageFor(m => m.JointAdditionalIncomeAmt)
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-9 ">
<div class="col-md-4">
<input type="submit" value="Continue" class="btn btn-default" />
</div>
</div>
</div>
}
If I understood what you trying to do is you want to return the partial view with the validation if it fail ( Model state) and you need to redirect or pass another one if modelstate is valid.
If you want to do above scenario you can do combination of jquery and json
Submit the form using jquery (Serialized form) to the post method and return the json result if you want to redirect to somewhere else
please correct me if I am wrong.
Ok you are in right track just try these few steps.
Put a condition on your controller to your model state is valid or not
On your controller you need to return the json object which has the route url with the parameters.
On controller
return Json( new { redirectToAction = Url.Action( "ActionResult", "Controller", new {Parameters = parameters } ) } );
And you jquery function should be
For default bind add pass your url as a string to the jquery function.
function SubmitForm(routUrl) {
var serializedForm = $("# YourFormName ").serialize();;
$.ajax({
url: routUrl,
cache: false,
type: "POST",
data: serializedForm,
success: function (data) {
if (data.redirectToAction) {
window.location.href = data.redirectToAction;
}
else {
$("#YourFormName").html(data);
}
}
});
}
Let me know if you need more details, hope this will help you.

Categories

Resources