MVC Compare not working - asp.net-mvc

I'm having problems validating 2 textboxes using the [Compare-attribute. Even if they're same the client validation says they're different.
In my editmodel I have:
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Password not matching")]
public string ConfirmPassword { get; set; }
In view:
<tr>
<td class="editor-label">
#Html.LabelFor(model => model.User.Password):
</td>
<td class="editor-field">
#Html.EditorFor(model => model.User.Password)
#Html.ValidationMessageFor(model => model.User.Password)
</td>
</tr>
<tr>
<td class="editor-label">
#Html.LabelFor(model => model.User.ConfirmPassword):
</td>
<td class="editor-field">
#Html.EditorFor(model => model.User.ConfirmPassword)
#Html.ValidationMessageFor(model => model.User.ConfirmPassword)
</td>
</tr>
Textboxes gets rendered as:
<input class="text-box single-line password" data-val="true"
data-val-required="Password missing" id="User_Password"
name="User.Password" type="password" value="" />
<input class="text-box single-line password" data-val="true"
data-val-equalto="Password not matching"
data-val-equalto-other="*.Password" id="User_ConfirmPassword"
name="User.ConfirmPassword" type="password" value="" />
<span class="field-validation-valid" data-valmsg-for="User.ConfirmPassword"
data-valmsg-replace="true"></span>
What might be wrong/missing here?

I updated unobtrusive + jquery validation using the Nuget packagemanager. And that did the trick

Related

MVC 5 ActionResult parameter always null

I'm pretty newbie with MVC and my English is very poor. I'm now stuck with a parameter always being null in my ActionResult parameter.
Here is the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "TimeCodeId, Code, Title, Description, IsValid, DateCreated")] TimeCodeInfo infoTimeCode, string submitButton)
{
bool result;
switch (submitButton)
{
case "Update":
case "Enregistrer":
infoTimeCode.LastDateModified = DateTime.Now;
result = _mTimeCode.Update(infoTimeCode);
return RedirectToAction("List");
case "Cancel":
case "Annuler":
return RedirectToAction("List");
//break;
}
return View(infoTimeCode);
}
and this is the cshtml
#using (Html.BeginForm("Edit", "TimeCode", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(Model => Model.TimeCodeId)
<table class="w3-table w3-card">
<tr>
<td>Code:</td>
<td>
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</td>
</tr>
<tr>
<td>Titre:</td>
<td>
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</td>
</tr>
<tr>
<td>Description:</td>
<td>
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</td>
</tr>
<tr>
<td>Est valide ?</td>
<td>
#Html.EditorFor(model => model.IsValid)
#Html.ValidationMessageFor(model => model.IsValid)
<label class="switch" onsubmit="#Model.IsValid = getCheckBoxValue('switchCheckBox')">
<input id="switchCheckBox" type="checkbox" name="IsValid">
<span class="slider round"></span>
</label>
</td>
</tr>
<tr>
<td>Date de création:</td>
<td>#Model.DateCreated</td>
</tr>
<tr>
<td>Dernière modification:</td>
<td>#Model.LastDateModified</td>
</tr>
</table>
<br />
<i class="fa fa-caret-left"></i> Retour à la liste
<div class="float-right">
<button type="submit" value="enregistrer"> enregistrer </button>
#*<a type="submit" href="~/Views/TimeCode/List.cshtml" class="w3-right w3-round-medium button buttonBlue">Enregistrer</a>*#
Annuler
</div>
}
Parameter submitButton is always null when I debug it. Is someone seeing where the problem is? Do I have to add more details?
Thank you!

ReleaseDate data not persisting in Edit View ASP.NET MVC

I have the following Index view:
#model IEnumerable<MVCMovie3.Models.Movie>
#{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-controller="Movies" asp-action="Index">
<p>
Title: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="#item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="#item.ID">Delete</a>
</td>
</tr>
}
</table>
And here is the "Edit" view listed in the Index view:
#model MVCMovie3.Models.Movie
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form asp-action="Edit">
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ID" />
<div class="form-group">
<label asp-for="Genre" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Price" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Rating" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Rating" class="form-control" />
<span asp-validation-for="Rating" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
My problem is that everything shows fine on the Index view but when I click the link to bring up the Edit view the release date is gone. Any suggestions?
Also, here is my model that I generated the views off of:
using System;
using System.ComponentModel.DataAnnotations;
namespace MVCMovie3.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public string Rating { get; set; }
public decimal Price { get; set; }
[Display(Name = "ReleaseDate")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
}
}
In playing around with it I've found that if I take off the [Display(Name.... and [DisplayType.... parts then it runs fine, except now my release date is not in the format I want it to be in. Help please.....
For now the only fix that i have found is to change the following code:
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
To:
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime ReleaseDate { get; set; }
This is, to remove the ApplyFormatInEditMode = true from the DisplayFormat line.
No the less as i mentioned before this would make the DatePicker field to show a date format in the form dd-MM-yyyy (the default one) and not the one you selected.

ASP.NET MVC 4 Model property value lost coming back from Edit view

I have a model with a DateCreated value that is not scaffolded. Coming to GET Edit controller action I see that the model has a correct value that is passed on to the Edit view. Coming back from the view, POST method, the value for DateCreated is DateTime default. It's lost.
Does anyone know why? Controller and View are scaffolded.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product)
{
try
{
if (ModelState.IsValid)
{
product.DateEdited = DateTime.Now;
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException dex)
{
Console.Write(dex.Message);
ModelState.AddModelError("", reg6.Resources.UnableToSaveChanges);
}
return View(product);
}
#model reg6.Models.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
<div>
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
<div>
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.BasePrice)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.BasePrice)
<div>
#Html.ValidationMessageFor(model => model.BasePrice)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</td>
<td align="right">
<input type="submit" value="Create" id='CreateButton' />
<td>
</tr>
</table>
</fieldset>
}
In your view place a hidden element for the DateCreated
#Html.HiddenFor(m=>m.DateCreated)
All the hidden elements will be posted to the server.

Disable unobtrusive validation on an ASP.NET MVC form

I have two forms on a page. I want the first form to use unobtrusive validation, as it's since automatically generated by ASP.NET MVC Framework. There is a second form, however, which I wrote manually, that should not use unobtrusive validation.
Here's some code:
#using (Html.BeginForm("Add", "Contacts", FormMethod.Post, new { id = "AddForm" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Datos Contacto</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ContactDepartmentID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ContactDepartmentID, (List<SelectListItem>)ViewBag.ContactDepartments)
#Html.ValidationMessageFor(model => model.ContactDepartmentID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Sex)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Sex, (List<SelectListItem>)ViewBag.Sexs)
#Html.ValidationMessageFor(model => model.Sex)
</div>
</fieldset>
<br />
#Html.HiddenFor(model => model.SerializedEmails, new { data_bind = "value: ko.toJSON($root.emails())" })
#Html.HiddenFor(model => model.SerializedPhones, new { data_bind = "value: ko.toJSON($root.phones())" })
}
<form id="phoneForm" >
<fieldset>
<legend>Teléfonos</legend>
<table class="table">
<tbody data-bind="foreach: phones">
<tr>
<th>
Celular?
</th>
<th>
Phone
</th>
<th>
Extension
</th>
<th>
</th>
</tr>
<tr>
<td>
<input type="checkbox" data-bind="checked: isMobile" />
</td>
<td>
<input class="phone" data-bind='value: phone'/>
</td>
<td>
<input type="text" class="extension" data-bind='value: phoneExtension, enable: !isMobile() ' />
</td>
<td>
<a href='#' data-bind='click: $root.removePhone'>Delete</a>
</td>
</tr>
</tbody>
</table>
<a href='#' data-bind='click: $root.addPhone'>Agregar teléfono</a>
</fieldset>
</form>
<p>
<button onclick="Submit();" type="button" class="btn btn-primary" data-bind='enable: phones().length > 0 || emails().length > 0'>
Create</button>
</p>
JS:
function Submit()
{
var valid = $('#AddForm').valid();
var valid2 = $('#phoneForm').valid();
}
jQuery.validator.addClassRules("phone", {
required: true
});
As a side note: When I remove the unobtrusive validation from the page, the second form validates, but the first does not. If I use unobtrusive validation the first form validates, but the second form does not.
I know I can do the whole validation on the client side—and, if that's the only way, I will do it. I was thinking about a way to continue using unobtrusive validation, but allowing it to be conditionally disabled using e.g. custom attributes.
You can disable the unobtrusive validation from within the razor code via this Html Helper property:
HtmlHelper.ClientValidationEnabled = false;
That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.
You can mark the elements or find it all the input of the second form and remove the rules, this sample is for remove all rules of some controls in the form, this cause according with the user selected some options, the values required will be others. for this reason i store the rules to restore it later.
///Remove rules
$("input.rO,textarea.rO").each(function () {
try
{
var rule = $(this).rules();
if (rule) {
$(this).data("rule", rule);
$(this).rules("remove");
}
}
catch(err){}
});
///Restore rules
$("input.rO.om" + v + ",textarea.rO.om"+v).each(function () {
try
{
var rule = $(this).data("rule");
if (rule)
$(this).rules("add", rule);
}
catch(err){}
});

ASP.NET MVC [Required] does not trigger

As the title says my Required field does not trigger.
This is my ViewModel class its name is SignUpForm.cs
public class SignUpForm
{
[Required]
[StringLength(100,ErrorMessage="You must enter a your firstname!",
MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "You must enter a your surname!",
MinimumLength = 1)]
public string SurName { get; set; }
}
This is my Razor view! Name of view is Step2.cshtml
#model MvcApplication2.Models.ViewModel.SignUpForm
#{
ViewBag.Title = "Step2";
}
<div id="content-header">
<h1 class="title">Complete your registration</h1>
</div>
<div id="content-area">
<h4>Fill in the form below to complete your registration
</h4>
#using(Html.BeginForm("testar","Interested", FormMethod.Post))
{
<h3>Personal information</h3>
<p class="app-label">Surname<span class="requiredField">*</span></p>
<div class="editor-label">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<p class="app-label">Surname<span class="requiredField">*</span></p>
<div class="editor-label">
#Html.EditorFor(model => model.SurName)
#Html.ValidationMessageFor(m => m.SurName)
</div>
}
Source as Requested
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-2.5.3.js" type="text/javascript"></script>
<link href="/Content/remigium.css" rel="stylesheet" />
<h3>Personal information</h3>
First name<span class="requiredField">*</span>
<div class="editor-label">
<input class="text-box single-line" data-val="true" data-val-length="You must enter a your firstname!" data-val-length-max="100" data-val-length-min="1" data-val-required="The FirstName field is required." id="FirstName" name="FirstName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
</div>
<p class="app-label">Surname<span class="requiredField">*</span></p>
<div class="editor-label">
<input class="text-box single-line" data-val="true" data-val-length="You must enter a your surname!" data-val-length-max="100" data-val-length-min="1" data-val-required="The SurName field is required." id="SurName" name="SurName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="SurName" data-valmsg-replace="true"></span>
</div>
I was missing these script references, I added them and all was cool!
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Resources