ValidationMessageFor automatically getting fred - c#

I have an actionmethod resetpassword which is of type get which returns a view. The method gets called from an actionlink button. To this view I am passing a user obj. Now when I click on the actionlink , it goes to the view but as I have applied validationfor the validations are getting fired automatically when the view is loaded. Is this because I am passing an obj of user to the view.? If that's the case, then how can i turn off the validations for HttpGet for that action method as I only want to load the inputs and when the user starts filling in the inputs then only validation should fire.
Action Method.
[ValidateInput(false)]
[HttpGet]
[ActionName("ResetPassword")]
public ActionResult ResetPassword(UserBE user)
{
user.Email = TempData["userEmail"].ToString();
return View(user);
}
View
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#model XYZ.BE.UserBE
#{
ViewBag.Title = "ResetPassword";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ResetPassword</h2>
#using (Html.BeginForm("ResetPassword", "User"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model=>model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
#Html.HiddenFor(model=>model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.NewPassword)
#Html.ValidationMessageFor(model => model.NewPassword)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmedPassword, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.ConfirmedPassword)
#Html.ValidationMessageFor(model => model.ConfirmedPassword)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Reset Password" class="btn btn-default" />
</div>
</div>
}
ActionLink BUtton
<h3>#Html.ActionLink("Reset Password", "ResetPassword")
Post Method
[HttpPost]
[ActionName("ResetPassword")]
public ActionResult ResetPasswordPost(UserBE user)
{
user = UserBL.AuthenticateUser(user);
if (!user.AuthenticUser || (user.Password==user.NewPassword))
{
return View(user);
}
else
{
return UserBL.ResetPassword(user)?View("LoginSuccessful",user):View(user);
}
}
Model
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
private bool authenticUser = false;
public bool AuthenticUser
{
get { return authenticUser; }
set { authenticUser = value; }
}
[Required(ErrorMessage = "Password is required")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "Confirm passord and NewPassWord does not match")]
[Compare("NewPassword")]
public string ConfirmedPassword { get; set; }

I just added the following to _layout and it worked.
#Scripts.Render("~/bundles/jqueryval")

Related

ASP.NET MVC 5 Multi select not binding during POST

I am new to ASP.NET MVC 5 and having some issues with binding only the multi-select section of the body during POST when submitting the form. The form renders correctly, with checkboxes being correctly selected. The form is scaffolded using visual studio (except the multi-select)
public class EditViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "LastName")]
public string LastName { get; set; }
public IList<RolesViewModel> Roles { get; set; }
}
public class RolesViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool Selected { get; set; }
}
[HttpGet]
public async Task<ActionResult> Edit(string Id)
{...
var model = Mapper.Map<ApplicationUser, EditViewModel>(user);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditViewModel model)
{
}
#model BloggingService.Web.Models.EditViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#for (int i = 0; i < Model.Roles.Count; i++)
{
#Html.CheckBoxFor(x => #Model.Roles[i].Selected,"test1");
<div class="form-check">
<input type="hidden" asp-for="#Model.Roles[i].RoleId" />
<input type="hidden" asp-for="#Model.Roles[i].RoleName" />
<input type="checkbox" asp-for="#Model.Roles[i].Selected" class="form-check-input" checked="#Model.Roles[i].Selected" />
<label class="form-check-label" asp-for="#Model.Roles[i].Selected">
#Model.Roles[i].RoleName
</label>
</div>
}
</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>
Would really appreciate any insight.
I have managed to find the correct and cleaner approach for accomplishing such tasks by utilizing the HTML helper methods inside my for loop and now the data are able to bind correctly during data-binding.
#Html.HiddenFor(x => #Model.Roles[i].RoleId);
#Html.HiddenFor(x => #Model.Roles[i].RoleName);
#Html.CheckBoxFor(x => #Model.Roles[i].Selected);

Asp.NET MVC Client side validation is not working

whenever I am submitting the form without entering the required fields instead of giving an immediate client-side validation error it is going to the Httppost Actionresult Index method allowing to submit the form. After roundtrip to server-side then giving errors. I have added reference of jquery.validate.js, unobtrusive.js both libraries, and also set ClientValidationEnabled and UnobtrusiveJavaScriptEnabled value true inside web.config. YOUR KIND HELP WILL BE HIGHLY APPRECIATED
HTML :
#model binaryquest.web.CustomModels.ContactVM
#{
ViewBag.Title = "Home Page";
}
<div id="contact" class="form">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>CONTACT</h2>
<ul class="list-unstyled li-space-lg">
<li class="address">Don't hesitate to give us a call or just use the contact form below</li>
</ul>
</div> <!-- end of col -->
</div> <!-- end of row -->
<div class="row">
<div class="col-lg-8 offset-lg-2">
<!-- Contact Form -->
<form action="/Home/Index" method="post">
#Html.AntiForgeryToken()
#Html.ValidationMessage("expired", new { #class = "text-danger" })
#Html.ValidationMessage("CaptchaFail", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "required" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "required" })
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "required" })
#Html.EditorFor(model => model.Message, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
<div class="form-group checkbox">
<input type="checkbox" id="cterms" value="Agreed-to-Terms" required>I have read and agree to Leno's stated conditions in Privacy Policy.
<div class="help-block with-errors"></div>
</div>
#Html.CheckBoxFor(model => model.IsTermsAccepted, new { htmlAttributes = new { #class = "form-control" } })
#Html.LabelFor(model => model.IsTermsAccepted, htmlAttributes: new { #class = "required" })
#Html.ValidationMessageFor(model => model.IsTermsAccepted, "", new { #class = "text-danger" })
<div class="form-group">
<button type="submit" class="form-control-submit-button">SUBMIT MESSAGE</button>
</div>
<div class="form-message">
<div id="cmsgSubmit" class="h3 text-center hidden"></div>
</div>
</form>
<!-- end of contact form -->
</div> <!-- end of col -->
</div> <!-- end of row -->
</div> <!-- end of container -->
</div>
#section scripts{
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
}
MODEL :
public class ContactVM
{
[Required(ErrorMessage = "You must provide Name")]
[DisplayName("Name")]
public string Name { get; set; }
[Required(ErrorMessage = "You must provide an Email address")]
[DisplayName("Email")]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "You must provide Message")]
[DisplayName("Your Message")]
public string Message { get; set; }
[Display(Name = "Terms and Conditions")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the terms and conditions!")]
public bool IsTermsAccepted { get; set; }
}
CONTROLLER:
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Index(ContactVM model)
{
string sendGridKey ="";
if (ModelState.IsValid)
{
SendMail(model, sendGridKey);
return RedirectToAction("Thanks", "Home");
}
return View(model);
}
You need to use the loaded javascript. Add to your view the following:
<script>
$(document).ready(function() {
$.validator.unobtrusive.parse($("#myForm"));
}
function onSubmit(e) {
$("#myForm").validate(); // this will validate the form and show the validation messages
if($("#myForm").valid()) {
$("#myForm").submit(); // submits the form
}
// stop the postback
e.preventDefault();
}
</script>
Then on your form element:
<form id="myForm" onsubmit="onSubmit();" action="/Home/Index">
Seems validation scripts not loaded. Did you loaded in _layout.cshtml?
#RenderSection("scripts", required: false)
And try adding validation summery in starting of form
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
You can visit this link below
https://www.tutorialsteacher.com/articles/enable-client-side-valiation-in-mvc
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

How can I set a validationmessage for inputfield binded to entitymodel?

How can i set a validation message on all of these fields? Im not sure how to set it when I bind everything directly to my entitymodel Cancellation? I tried setting a validationmessage directly in my entityclass nut no luck.
This is my razorpage
#page
#model Index
#{
ViewBag.Title = "Index";
}
<div class="body-content">
<form id="avboka-form" method="post">
#Html.AntiForgeryToken()
<div class="form-group">
<div class="col-med-5">
<label asp-for="Cancellation.Elev"></label>
<input type="text" id="elev" asp-for="Cancellation.Elev" class="form-control">
<span asp-validation-for="Cancellation.Elev"></span>
</div>
</div>
<div class="form-group">
<div class="col-med-5">
<label asp-for="Cancellation.Dag"></label>
<input asp-for="Cancellation.Dag" type="datetime" id="datepicker" class="datepicker1 form-control">
<span asp-validation-for="Cancellation.Dag"></span>
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => Model.SelectedKommun, htmlAttributes: new { #class = "control-label col-med-2" })
<div class="col-med-5">
#Html.DropDownListFor(x => Model.Cancellation.KommunId, new SelectList(Model.Kommun, "Value", "Text"), htmlAttributes: new { #class = "form-control", id = "kommun" })
#Html.ValidationMessageFor(x => x.SelectedKommun, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => Model.SelectedFordon, htmlAttributes: new { #class = "control-label col-med-2" })
<div class="col-med-5">
#Html.DropDownListFor(x => Model.Cancellation.FordonId, new SelectList(Model.Fordon, "Value", "Text"), htmlAttributes: new { #class = "form-control", #id = "fordon" })
#Html.ValidationMessageFor(x => x.SelectedFordon, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-med-5">
<label asp-for="Cancellation.Skola.Namn"></label>
<select id="skola" name="Cancellation.SkolaId" class="form-control">
#foreach (var schools in Model.School)
{
<option value="#schools.Id">#schools.Namn</option>
}
</select>
<span asp-validation-for="Cancellation.SkolaId"></span>
</div>
<input type="submit" name="save" value="Avboka skolskjuts" class="vt-btn" />
</form>
</div>
Here is part of my pagemodel where i bind my input-fields. The selects is collected from other tables and therefore is never empty.
[BindProperty]
public Avbokning Cancellation { get; set; }
public Index(SqlAvbokningData<Avbokning> avbokningRepo, SqlKommunData<Kommun> kommunRepo, SqlFordonData<Fordon> fordonRepo, SqlSkolaData<Skola> skolaRepo)
{
_avbokningRepo = avbokningRepo;
_kommunRepo = kommunRepo;
_fordonRepo = fordonRepo;
_skolaRepo = skolaRepo;
}
public async Task<IActionResult> OnGet()
{
Kommun = await _kommunRepo.GetKommuner();
Fordon = _fordonRepo.GetFordon();
Municipalities = await _kommunRepo.GetAll();
Vehicle = await _fordonRepo.GetAll();
School = await _skolaRepo.GetAll();
return Page();
}
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
//if (!Cancellation.Validate())
// return Redirect("/");
await _avbokningRepo.Add(Cancellation);
return Redirect("/Tack");
}
return RedirectToAction("OnGet");
}
Validation in MVC can be done with a viewmodel. You specify your model this way:
public class LogOnViewModel
{
[Required(ErrorMessage = "RequiredField")]
[Display(Name = "Username")]
public string Username { get; set; }
[Required(ErrorMessage = "RequiredField")]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
Once you get to the web page itself, the ValidationMessageFor will then validate the fields based on the data annotations you have placed on your viewmodel, as you pass that on to the web page.
In the controller you can pass it on to the page by means like this:
var viewModel = new LogOnViewModel();
// do stuff
return View(viewModel);
It's not a perfect example, but this should give some idea of how you can use it.

MVC Form does not pass Model on Submit

I have the following MVC View and Controller. When I submit the form. It pass in the Id instead of the ChangeUserViewModel.
View:
#model AppTransactionsManagement.Models.ChangeUserViewModel
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Change Password</h4>
</div>
#using (Html.BeginForm("ChangePassword", "UsersAdmin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>
}
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
private async Task<ActionResult> ChangePassword(ChangeUserViewModel model)
{
if (ModelState.IsValid)
{
//Get the user manager and user. (if the user is not found, user will be null)
ApplicationUser user = await UserManager.FindByIdAsync(model.Id);
if (user == null)
{
return PartialView("_ChangePassword");
}
else
{
user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password);
UserManager.UpdateSecurityStamp(user.Id.ToString());
//Save Changes
IdentityResult result = await UserManager.UpdateAsync(user);
if (result.Succeeded)
{
return Json(new { success = true });
}
else
{
var error = result.Errors.FirstOrDefault();
return PartialView("_ChangePassword");
}
}
}
return PartialView("_ChangePassword");
}
Model:
public class ChangeUserViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
What am I doing wrong?
You have marked the method as private, which will make it inaccessible. You can't POST to a private method. This is most likely your problem. Change it to
[HttpPost]
public async Task<ActionResult> ChangePassword(ChangeUserViewModel model)
{
......
......
}
Try to use model binding in your controller action.
public async Task<ActionResult> ChangePassword([Bind(Include = "Id, Email, Password")]ChangeUserViewModel model) {}

Postback when validating ASP.NET MVC Form

I created a web form form using asp.net mvc scaffolding and it does not work client side validation without postback. [Required()] is postbacking and [EmailAddress] validator is validating in client side. Im using visual studio 2013 and asp.net mvc 5 with ef6.
this id my model class :
namespace WebApplication4.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Tutor
{
public Tutor()
{
this.Examinations = new HashSet<Examination>();
}
public decimal TutorID { get; set; }
[Display(Name = "First Name ")]
[Required(ErrorMessage = "Please Enter First Name.")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Display(Name = "Last Name ")]
[Required(ErrorMessage = "Please Enter Last Name.")]
[DataType(DataType.Text)]
public string LastName { get; set; }
[Display(Name = "Address Line 1 ")]
[Required(ErrorMessage = "Please Enter Address Line 1.")]
[DataType(DataType.Text)]
public string Address1 { get; set; }
[Display(Name = "Address Line 2 ")]
[Required(ErrorMessage = "Please Enter Address Line 2.")]
[DataType(DataType.Text)]
public string Address2 { get; set; }
[Display(Name = "Address Line 3 ")]
public string Address3 { get; set; }
[Display(Name = "Telephone 1 ")]
[Required(ErrorMessage = "Please Enter Telephone No.")]
[DataType(DataType.Text)]
public string Tel1 { get; set; }
[Display(Name = "Telephone 2 ")]
[DataType(DataType.Text)]
public string Tel2 { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "Please Enter E Mail Address.")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[DataType(DataType.EmailAddress)]
public string EMail { get; set; }
[Display(Name = "Password ")]
[DataType(DataType.Password)]
public string Password { get; set; }
public Nullable<bool> IsConfirmed { get; set; }
public virtual ICollection<Examination> Examinations { get; set; }
}
}
This is my controller Create() methods in controller:
// GET: /Default1/Create
public ActionResult Create()
{
return View();
}
// POST: /Default1/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="TutorID,FirstName,LastName,Address1,Address2,Address3,Tel1,Tel2,EMail,Password,IsConfirmed")] Tutor tutor)
{
if (ModelState.IsValid)
{
db.Tutors.Add(tutor);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tutor);
}
This Is view for create...
#model WebApplication4.Models.Tutor
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Tutor</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address1)
#Html.ValidationMessageFor(model => model.Address1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address2)
#Html.ValidationMessageFor(model => model.Address2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address3, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address3)
#Html.ValidationMessageFor(model => model.Address3)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Tel1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Tel1)
#Html.ValidationMessageFor(model => model.Tel1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Tel2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Tel2)
#Html.ValidationMessageFor(model => model.Tel2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EMail, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EMail)
#Html.ValidationMessageFor(model => model.EMail)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I want to validate all the things in client side.
Make sure you load jquery.validate.js liberary properly
BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
At end of your page
#Scripts.Render("~/bundles/jqueryval")
Solution is to use jquery.validate.unobtrusive.js.
Once you load the form, using jquery on document ready you should parse the form
//file: your view file
#model Tutor
<script>
$(document).ready(function() {
$.validator.unobtrusive.parse($("#frm1"));
}
function onSubmit(e) {
$("#frm1").validate(); // this will validate the form and show the validation messages
if($("#frm1").valid()) {
$("#frm1").submit(); // submits the form
}
return false;//prevent default submit of form by returning false.
//also e.preventDefault() can be used.
}
</script>
//for understanding purpose using the plain form tag.
//one can use #using (Html.BeginForm())
<form id="frm1" onsubmit="onSubmit();">
<!-- your content goes here -->
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
</form>

Categories

Resources