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.
Related
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")
I have a scaffolded "create" view that, when I ty to create a new record, returns the error: System.Web.Mvc.WebViewPage<TModel>.Model.get returned null. Even before I pressed "save".
My model:
namespace Itucation.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("jobcoach")]
public partial class jobcoach
{
public int kursist_id { get; set; }
//[Column(TypeName = "text")]
public string note { get; set; }
[Key]
public int jobcoach_note_id { get; set; }
[Column("status")]
//[StringLength(50)]
[Display(Name = "Status")]
public string status { get; set; }
[Column(TypeName = "date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Success dato")]
public DateTime? succesDato { get; set; }
public int? AntalSamtaler { get; set; }
public virtual kursister kursister { get; set; }
}
}
My controller:
// GET: jobcoach/Create
public ActionResult Create(int? id)
{
ViewBag.kursist_id = new SelectList(db.kursister, "kursist_id", "fornavn");
ViewBag.status = new SelectList(db.JobcoachStatus, "status", "status");
ViewBag.ID = id;
ViewBag.kursist = (from k in db.kursister
where k.kursist_id == id
select k);
//var jc = db.jobcoach.Where(u => u.kursist_id == id).ToList().FirstOrDefault();
var jc = db.jobcoach.Where(r => r.kursist_id == id).ToList().FirstOrDefault();
if (jc == null)
{
// param is not set
}
else
{
return RedirectToAction("Edit/" + jc.jobcoach_note_id);
}
return View();
}
// POST: jobcoach/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "jobcoach_note_id,kursist_id,note,status,succesDato, AntalSamtaler")] jobcoach jobcoach)
{
if (ModelState.IsValid)
{
//Brugernavn (current user) skal også indsættes
jobcoach.note = jobcoach.note + " Af " + User.Identity.Name + " - " + DateTime.Now.ToString();
db.jobcoach.Add(jobcoach);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.kursist_id = new SelectList(db.kursister, "kursist_id", "fornavn", jobcoach.kursist_id);
return View(jobcoach);
}
My View:
#model Itucation.Models.jobcoach
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div>
<h4>jobcoach</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div>
#Html.LabelFor(model => model.kursist_id, "Kursist", htmlAttributes: new { #class = "control-label " })
<div>
#{
foreach (var navn in (ViewBag.kursist))
{
<text>Kursist ID: </text>#navn.kursist_id <br />
<text>Navn:</text> #navn.fornavn<text> </text> #navn.efternavn <br />
<text>E-mail: </text>#navn.mail
}
}
<input type="hidden" name="kursist_id" id="kursist_id" value="#ViewBag.ID" />
#*#Html.DropDownList("kursist_id", null, htmlAttributes: new { #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.kursist_id, "", new { #class = "text-danger" })
</div>
</div>
<div>
#Html.LabelFor(model => model.note, htmlAttributes: new { #class = "control-label " })
<div>
#Html.TextAreaFor(model => model.note, new { #class = "form-control", #cols = "100%", #rows = "20", #tabindex = "21" })
#Html.ValidationMessageFor(model => model.note, "", new { #class = "text-danger" })
</div>
</div>
<div>
Status
<div>
<select id="status">
<option value="Uden status">Uden status </option>
<option value="Ordinær uddannelse">Ordinær uddannelse</option>
<option value="Deltidsjob">Deltidsjob</option>
<option value="Praktik">Praktik</option>
<option value="Løntilskud privat">Løntilskud privat</option>
<option value="Løntilskud offentlig">Løntilskud offentlig</option>
<option value="Ordinært job">Ordinært job</option>
</select>
</div>
</div>
<div>
Success dato
<div>
<input type="date" id="succesDato" name="succesDato" />
</div>
</div>
<div>
Antal samtaler
<div>
<input type="text" id="AntalSamtaler" name="AntalSamtaler" value="#Model.AntalSamtaler"/>
</div>
</div>
#*<div>
#Html.LabelFor(model => model.status, htmlAttributes: new { #class = "control-label " })
<div>
<select id="status" name="status" class="form-control ">
<option>Vælg evt. en status</option>
<option value="Ordinært job">Ordinært job</option>
<option value="Ordinær uddannelse">Ordinær uddannelse</option>
<option value="Deltidsjob">Deltidsjob</option>
<option value="Praktik">Praktik</option>
<option value="Løntilskud privat">Løntilskud privat</option>
<option value="Løntilskud offentlig">Løntilskud offentlig</option>
</select>
</div>
</div>*#
<div class="form-group col-md-12">
<div class="col-md-offset-2 col-md-1">
<input type="submit" value="Opret" class="btn btn-default" />
</div>
</div>
</div>
}
<div class="col-md-10">
#Html.ActionLink("Tilbage til listen", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I would expect an "empty" view whith all the input fields, where I could input the date and the hit "save". Instead I get the error.
The error occurs at the line: #Html.ValidationMessageFor(model => model.note, "", new { #class = "text-danger" }).
I cannot seem to figure this out. I see many questions that refer to this error, but none seem to be applicable to my problem.
I would be very gratefull for any help.
This is because you're using a binding between the view and the model of type jobcoach. In the view if you want to bind the view to a model, you must pass it as a parameter at the View() method of controller, in this way:
jobcoach jc=new jobcoach();
return View(jc);
What you're trying to do now, is to render the create view from a "null" model, because you're using the #Html model-typed method helpers (LabelFor, ValidationMessageFor....)
So, when it tries to bind the view with the model, the error throws, because it hasn't the Model proerty setted into the view.
I found the problem: I was trying to acces #Model.AntalSamtaler, but that was null, since I hadn't saved it yet. I changed the line:
<input type="text" id="AntalSamtaler" name="AntalSamtaler" value="#Model.AntalSamtaler"/>
to:
<input type="text" id="AntalSamtaler" name="AntalSamtaler" value="1"/>
I made this mistake by copy/pasting from the "edit" view, where #Model.AntalSamtaler was set.
I'm having following FinanceProductFeatures table , I want show each of this table record as label name for a form.
So I created model class like this
public class ProductFinanceFeatures
{
public IList<AB_FinanceProductFeatures> ListProductFinanceFields { get; set; }
}
public partial class AB_FinanceProductFeatures
{
public string ProductFinanceNameEn { get; set; }
public string ProductFinance_Value_EN { get; set; }
}
then Controller class like this
[HttpGet]
public ViewResult Financing_Product_Feature_Configuration()
{
var model = new ProductFinanceFeatures
{
ListProductFinanceFields = db.FinanceProductFeatures.ToList()
};
return View(model);
}
then Its viewpage like this
#model albaraka.Models.ProductFinanceFeatures
#{
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#for (int i = 0; i < Model.ListProductFinanceFields.Count; i++)
{
<div class="form-group">
#Html.LabelFor(model => model.ListProductFinanceFields[i].ProductFinanceNameEn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(m => m.ListProductFinanceFields[i].ProductFinance_Value_EN, new { #row = 5 })
</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>
}
but here I'm not getting expected result, cannot render the Label
showing like this
Just simply replace TextAreaFor with DisplayFor as below-
<div class="col-md-10">
#Html.DisplayFor(m => m.ListProductFinanceFields[i].ProductFinance_Value_EN, new { #row = 5 })
</div>
Or
<div class="col-md-10">
#Html.DisplayTextFor(m => m.ListProductFinanceFields[i].ProductFinance_Value_EN)
</div>
Hope this works for you..!
I am fairly new to MVC5 and C# and I am trying to achieve something that I don't fully understand.
I have a Team Model such as this:
public class Team
{
[Key]
public Guid ID { get; set; }
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
}
I also have a Player Model such as this:
public class Player
{
[Key]
public Guid Id { get; set; }
[ForeignKey("Teams")]
public Guid TeamId { get; set; }
public string Name { get; set; }
public virtual Team Teams { get; set; }
}
View Model is
public class TeamViewModel
{
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
public List<Player> Players { get; set; }
}
With this structure, you are suppose to be able to add and infinite number of players to each team. As such I have a Teams table with few properties and a Player table that contains the player name as well as the player TeamId so that we know to what team they belong.
My problem comes when I am creating a team. I have Create Controller such as this:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(TeamViewModel model)
{
if (ModelState.IsValid)
{
var team = new Team { TeamName = model.TeamName, Coach = model.Coach, Conference = model.Conference, Player = model.Player };
db.Teams.Add(team);
var result = await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View();
}
And my View is as follows:
#model SoccerTeams.Models.ViewModels.TeamViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Team</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TeamName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TeamName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TeamName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Coach, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Coach, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Coach, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Conference, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Conference, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Conference, "", new { #class = "text-danger" })
</div>
</div>
#if (#Model != null)
{
foreach (var p in Model.Player)
{
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">" + p.ToString() + "</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"Player\" type-\"text\"")
</div>
</div>
}
}
else
{
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">Player</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"Player\" type-\"text\"")
</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")
}
From my understanding, the View is suppose to be able to convert the input element to a list and pass it on to my ViewModel. However, my ViewModel is always coming up as null.
What am I missing and how would I make this work?
P.S. I understand that I can user Html.EditorFor, but I was not able to get it working, so I just printed it out as Html as I need to solve my other problem first.
Edit
I have altered my View to have the following code
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">Player</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"model.Players[0].Name\" type-\"text\"")
</div>
</div>
As a result, the model now properly populates the Players Array, however all other values have now become null. If I remove the input element, the values are populated but players array is null again as there are no form fields for it. Do you know what could be the culprit?
In the TeamViewModel I have also renamed Player to Players.
In order for MVC to bind your form data to the Action method's parameters
their names should match.
Supposing your ViewModel has property for List<Player> Players your code should be:
In your case:
foreach (var p in Model.Player)
{
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">" + p.ToString() + "</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"Player\" type-\"text\"")
</div>
</div>
}
Should be:
for (int i = 0; i < Model.Player.Length; i++)
{
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">" + p.ToString() + "</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"model.Player[" + i + "].Name\" type-\"text\"")
</div>
</div>
}
Because this is the name of the parameter that you have provided:
Create(TeamViewModel model)
Also be careful because the indexes should not be broken, which means that they should be 0, 1, 2.. etc. without skipping a number.
The way that we read in the properties is by looking for
parameterName[index].PropertyName. The index must be zero-based and
unbroken.
NOTE You can read more about binding collections in Scott Hanselman's post - here
And last I suggest if you have a property that is list of something - in your case list of Player to use the plural form for the property name - Players.
EDIT
Try removing the "model." in front in the name. Make it like this "Players[0].Name". Since you only have one parameter in your Create Action method it should be fine.
I suggest you to use the helper #Html.EditorFor, so to do this you will create a partial view that will be used as template to inputs of the nested property. see the example:
Shared/EditorTemplates/Player.cshtml
#model Player
<div class="form-group">
#Html.HiddenFor(e => e.Id)
#Html.HiddenFor(e => e.TeamId)
<label class="control-label col-md-2" for="player">Player</label>
<div class="col-md-10">
#Html.TextBoxFor(e => e.Name, new { #class = "form-control text-box single-line", id = "player", name = "Player"})
</div>
</div>
Players form on Team view:
#Html.EditorFor(e => e.Player)
Instead of:
foreach (var p in Model.Player)
{
<div class="form-group">
#Html.Raw("<label class=\"control-label col-md-2\">" + p.ToString() + "</label>")
<div class="col-md-10">
#Html.Raw("<input class=\"form-control text-box single-line\" name=\"Player\" type-\"text\"")
</div>
</div>
}
See this article for more information about editor templates: Editor and display templates
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")