Missing form validation in MVC application - c#

I have a form containing only check boxes, and I know that I can make each one required to enforce validation errors. But what I am looking for, is an error if none of the boxes has been checked. How would I go about achieving this?
I am looking for an error message like: "You must select at least one property."
I should clarify that none of the fields are required individually, there should just be at least one chosen option.
Edit for clarification:
My view looks something like this:
#using (Html.BeginForm("Method", "Controller", FormMethod.Post, new {id = "id"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Property1, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Property2, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Property3, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property3)
</div>
</div>
}
My View model looks something like this:
public class FormVM
{
[Display(Name = "One")]
public bool Property1 {get;set;}
[Display(Name = "Two")]
public bool Property2 {get;set;}
[Display(Name = "Three")]
public bool Property3 {get;set;}
}

You can implement the IValidatableObject interface on your viewmodel:
public class FormVM : IValidatableObject
{
[Display(Name = "One")]
public bool Property1 {get;set;}
[Display(Name = "Two")]
public bool Property2 {get;set;}
[Display(Name = "Three")]
public bool Property3 {get;set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (!(Property1 || Property2 || Property3))
{
results.Add(new ValidationResult("You must select at least one property."));
}
return results;
}
}
The benefit of using this is that this will be fired automatically if you call ModelState.IsValid in your controller, and the error message added to the ModelState errors.

If this validation is to be used in one place only, then you can validate it in the Action method:
[HttpPost]
public ActionResult MyAction(FormVM model)
{
if (!(model.Property1 || model.Property2 || model.Property3))
{
ModelState.AddModelError(nameof(model.Property1), "You must select at least one");
}
if (ModelState.IsValid)
{
// Do something
}
return View(model);
}
If you are likely to be reusing this validation a lot more, I would suggest writing a validation attribute.

Since the question doesn't mention which server-side or client-side validation were preferred to use, there are 2 approaches.
1) Server-side validation (without ModelState.AddModelError):
Controller.cs
[HttpPost]
public ActionResult Method(FormVM model)
{
if (ModelState.IsValid)
{
// ... other processing code and action returns
}
if (!(model.Property1 || model.Property2 || model.Property3))
{
ViewData["Error"] = "You must select at least one property." // this can be changed with ViewBag
// immediately return the same page
return View(model);
}
}
View.cshtml:
<p>#ViewData["Error"]</p>
2) Client-side validation with vanilla JS, using id to identify required elements:
<script type="text/javascript">
var check1 = document.getElementById("check1").value;
var check2 = document.getElementById("check2").value;
var check3 = document.getElementById("check3").value;
if (!(check1 || check2 || check3))
{
document.getElementById("error").innerHTML = "You must select at least one property.";
}
else
{
document.getElementById("error").innerHTML = '';
}
</script>
<div class="form-group">
#Html.LabelFor(model => model.Property1, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property1, htmlAttributes: new { #id = "check1" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Property2, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property2, htmlAttributes: new { #id = "check2" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Property3, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.CheckBoxFor(model => model.Property3, htmlAttributes: new { #id = "check3" })
</div>
</div>
</div>
<div id="error"></div>

Related

Remote validation not working in ASP.NET MVC 5

Here I have create form which consists customer email field for which I am trying to check whether the entered email already exits or not and if exist show email already exists message.
To do this i have tried to use remote validation but the problem is that its not showing any error even though email exists, it not even hitting the controller in IsEmailExists method which is used for remote validation
Any help with my code will be a great help. Thank you
Below is my action in controller
public JsonResult IsEmailExists(string CustomerEmail)
{
emedicineEntities _db = new emedicineEntities();
return Json(!_db.Customers.Any(x => x.CustomerEmail == CustomerEmail), JsonRequestBehavior.AllowGet);
}
Below is my metadata
namespace eMedicine.Model
{
public class CustomerMetaDta
{
[Remote("IsEmailExists", "Customers", ErrorMessage = "EmailId already exists.")]
[Required(ErrorMessage = "Please Enter Emailw")]
public string CustomerEmail { get; set; }
}
}
Below is my partial class
namespace eMedicine.Model
{
[MetadataType(typeof(CustomerMetaDta))]
public partial class Customer
{
}
}
Below is my view consisting customer email
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm("Create", "Customers", FormMethod.Post, new { #id = "register" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CustomerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</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>
}
Change your method signature as follows to include the Bind Prefix attribute/property.
public JsonResult IsEmailExists([Bind(Prefix="Customer.CustomerEmail")] string CustomerEmail)
{
emedicineEntities _db = new emedicineEntities();
return Json(!_db.Customers.Any(x => x.CustomerEmail == CustomerEmail), JsonRequestBehavior.AllowGet);
}
Now it should work!
Not sure what real problem with your source code, but i tried to reproduce in my side, it worked well.
Here are my source code.
namespace WebApplication1.Controllers
{
public class CustomerMetaDta
{
[Remote("IsEmailExists", "Customer", ErrorMessage = "EmailId already exists.")]
[Required(ErrorMessage = "Please Enter Emailw")]
public string CustomerEmail { get; set; }
}
[MetadataType(typeof(CustomerMetaDta))]
public partial class Customer
{
}
public partial class Customer
{
public string CustomerEmail { get; set; }
public string CustomerName { get; set; }
public string PasswordHash { get; set; }
}
public class CustomerController : Controller
{
public JsonResult IsEmailExists(string CustomerEmail)
{
//emedicineEntities _db = new emedicineEntities();
List<Customer> _db = new List<Customer>
{
new Customer { CustomerEmail = "hien#gmail.com"},
new Customer { CustomerEmail = "hien1#gmail.com"}
};
return Json(!_db.Any(x => x.CustomerEmail == CustomerEmail), JsonRequestBehavior.AllowGet);
}
// GET: Customer
public ActionResult Index()
{
return View();
}
}
}
Index.cshtml file:
#model WebApplication1.Controllers.Customer
#{
ViewBag.Title = "Index";
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm("Create", "Customer", FormMethod.Post, new { #id = "register" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CustomerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CustomerEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</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>
}
It jumps to method IsEmailExists() and this is result output
May be you missed setting
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
in web.config?
If it's not hitting the controller that suggests it isn't a problem with the actual validation logic, but more an issue with how you're addressing the server.
There are a few things to check:
Is your remote validation code available to the client at all?
The first thing to consider is could this be a security/authentication issue. There are a few simple things you can do to check that:
If you have authentication attributes set on your controllers or methods, try commenting them out
try commenting out any other authentication code
If that doesn't fix it, then when you've got the app running in debug, try using Postman to call your remote validation endpoint and see whether:
Postman gets a 200 back from your method.
If so, put a breakpoint in your code and check it is actually getting executed.
If Postman can get to your endpoint then...
Is there an issue in your code?
I can't see anything obviously wrong in your code, but it is different to how I write validation code. This is an example of some working remote validation straight out of my code
This is the model property with the remote validation set:
[System.Web.Mvc.Remote(
action: "CheckExistingDocumentCode",
controller: "Documents",
AdditionalFields = "DocumentId",
HttpMethod = "POST",
ErrorMessage = "Code already exists")]
public string DocumentCode { get; set; }
This is the corresponding method in the Documents controller:
[HttpPost]
public async Task<ActionResult> CheckExistingDocumentCode(string DocumentCode, int DocumentId)
{
try
{
if (!await _documentValidationRules.IsExistingDocumentCodeAsync(DocumentCode, DocumentId))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("This Document Code is already in use", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
You can see that I've explicitly named all the parameters on the model property just to be clear exactly what's going on.
Comparing my code to yours the main differences are:
Mines async. That shouldn't make any difference.
My contrller method is a POST (so is has the HttpPost attribute, which also means I needed to tell the model the HttpMethod was POST too)
My remote validation method takes two parameters, so I'm passing in an extra property via the AdditionalFields argument
I can't see what the issue is in your code, but try changing it a piece at a time to work more like mine (particularly, try making it a post method and naming the parameters) and see if that exposes any issues.
Hopefully something in the above will get you closer.
One thing no one mentioned which will cause your symptons: If the method needs to be executed by Anonymous users and you don't have the AllowAnonymous attribute on your method, the method will not fire (and the submit button won't do anything.
You can try to add this code to the bottom of your View:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is the issue I had.
//[AcceptVerbs("Get,Post")]
//[AllowAnonymous]
public async Task<IActionResult> IsEmailInUse(string email)
{
var registration = await
_context.Registration.FirstOrDefaultAsync(m => m.Email == email);
if(registration == null)
{
return Json(true);
}
else
{
return Json($"Email {email} is already in use");
}
}
//In Model Class
public class Registration
{
[System.ComponentModel.DataAnnotations.Key]
public int EmpId { get; set; }
public string UserName { get; set; }
[Required]
[EmailAddress]
[Remote(action: "IsEmailInUse",controller: "Registrations")]
public string Email { get; set; }
}

ASP.Net MVC Unable to edit user because od the [Compare(Password)] in the class User

I have table named Korisnik (on my language, on english its User) and i added an Edit ActionResult in my Controller , but it wont work because of the [Compare("Lozinka")] that is comparing the password from the database and the added property PotvrdiLozinku, in other words i must enter the Confirm password in order to Submit the changes
namespace ProjekatFinalni.Models
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class Korisnik
{
public int KorisnikID { get; set; }
[DisplayName("Korisnicko ime:")]
[Required(ErrorMessage ="Molimo vas unesite korisnicko ime.")]
public string Korisnickoime { get; set; }
[DisplayName("Lozinka:")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Molimo vas unesite lozinku.")]
public string Lozinka { get; set; }
[DisplayName("Admin:")]
public bool DaLiJeAdmin { get; set; }
[DisplayName("Gost:")]
public bool Gost { get; set; }
[DisplayName("Pravo za unos:")]
public bool PravoUnosa { get; set; }
[DisplayName("Potvrdi lozinku:")]
[DataType(DataType.Password)]
[Compare("Lozinka",ErrorMessage ="Lozinke se ne poklapaju.")]
public string PotvrdiLozinku { get; set; }
public string LoginErrorPoruka { get; set; }
}
This is the Edit ActionResult in my controller
public ActionResult Edit(int id)
{
using (BazaProjekatEntities4 dbModel = new BazaProjekatEntities4())
{
return View(dbModel.Korisniks.Where(x => x.KorisnikID == id).FirstOrDefault());
}
}
[HttpPost]
public ActionResult Edit(int id,Korisnik k)
{
try
{
using (BazaProjekatEntities4 dbModel = new BazaProjekatEntities4())
{
dbModel.Entry(k).State = EntityState.Modified;
dbModel.SaveChanges();
}
return RedirectToAction("Izlistaj");
}
catch
{
return View();
}
}
And this is the Edit.cshtml
#model ProjekatFinalni.Models.Korisnik
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Korisnik</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.KorisnikID)
<div class="form-group">
#Html.LabelFor(model => model.Korisnickoime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Korisnickoime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Korisnickoime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Lozinka, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Lozinka, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Lozinka, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PotvrdiLozinku, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PotvrdiLozinku, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PotvrdiLozinku, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DaLiJeAdmin, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.DaLiJeAdmin)
#Html.ValidationMessageFor(model => model.DaLiJeAdmin, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gost, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Gost)
#Html.ValidationMessageFor(model => model.Gost, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PravoUnosa, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.PravoUnosa)
#Html.ValidationMessageFor(model => model.PravoUnosa, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Sacuvaj" class="btn btn-default" />
</div>
</div>
</div>
}
Only want to edit the permissions(Admin, Gost and PravoUnosa
EDIT( Added the registration form that i used)
[HttpPost]
public ActionResult DodajiliIzmeni(Korisnik korisnikmodel)
{
using (BazaProjekatEntities4 Modelkorisnik = new BazaProjekatEntities4())
{
if(Modelkorisnik.Korisniks.Any(x=> x.Korisnickoime == korisnikmodel.Korisnickoime))
{
ViewBag.DuplicateMessage = "Korisnicko ime vec postoji.";
return View("DodajiliIzmeni", korisnikmodel);
}
Modelkorisnik.Korisniks.Add(korisnikmodel);
Modelkorisnik.SaveChanges();
}
ModelState.Clear();
ViewBag.SuccessMessage = "Registracija je uspela";
return RedirectToAction("Index", "Login");
}
You should create a view model specific for the view, which has the properties and validation attributes on them as needed by the view and use that to transfer data between your view and action method.
public class EditUserVm
{
public int Id { get; set; }
[DisplayName("Korisnicko ime:")]
public string UserName { get; set; }
[DisplayName("Admin:")]
public bool Admin { get; set; }
[DisplayName("Gost:")]
public bool Gost { get; set; }
[DisplayName("Pravo za unos:")]
public bool PravoUnosa { get; set; }
}
Now you will use this view model for your GET and POST action methods. In your GET action method, first create an object of this view model, then get your Korisniks object for the Id passed in, Read and map the property values to the view model object and pass it to the view.
public ActionResult Edit(int id)
{
using (var dbModel = new BazaProjekatEntities4())
{
var user = dbModel.Korisniks.FirstOrDefault(x => x.KorisnikID == id);
// to do: If user is NULL, return a "Not found" view to user ?
var vm = new EditUserVm { Id = id };
vm.UserName = user.UserName;
vm.Admin = user.Admin;
vm.Gost = user.Gost;
vm.PravoUnosa = user.PravoUnosa;
return View(vm);
}
}
Now makes sure your view is strongly typed to this view model because we are passing an object of the EditUserVm class to it.
#model YourNamespaceGoesHere.EditUserVm
#using (Html.BeginForm())
{
#Html.HiddenFor(a=>a.Id)
<label>#Model.UserName</label>
#Html.LabelFor(a=>a.Admin)
#Html.CheckBoxFor(a=>a.Admin)
#Html.LabelFor(a=>a.Gost)
#Html.CheckBoxFor(a=>a.Gost)
#Html.LabelFor(a=>a.PravoUnosa)
#Html.CheckBoxFor(a=>a.PravoUnosa)
<button type="submit" >Save</button>
}
Now you will use the same view model as the action method parameter. Inside the method, we will read again the User entity from the database and udpate only the field we want to
[HttpPost]
public ActionResult Edit(EditUserVm model)
{
var db = new BazaProjekatEntities4();
var user = db.Korisniks.FirstOrDefault(x => x.KorisnikID == model.Id);
// to do : Do a null check on user to be safe :)
// Map the property values from view model to entity object
user.Admin = model.Admin;
user.Gost = model.Gost;
user.PravoUnosa = model.PravoUnosa;
db.Entry(k).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
In short, create a view model with properties absolutely needed by the view/ your code and use that to transfer data between your action method and view.
The solution was very simple and it could be from the start, i just need to add the user.PotvrdiLozinku = user.Lozinka; that will tell it that the Confirm password is equal to Password (For the [Compare] that is in the User class. :)
[HttpPost]
public ActionResult Edit(EditUserVm model)
{
var db = new BazaProjekatEntities4();
var user = db.Korisniks.FirstOrDefault(x => x.KorisnikID == model.Id);
// to do : Do a null check on user to be safe :)
// Map the property values from view model to entity object
user.Admin = model.Admin;
user.PotvrdiLozinku = user.Lozinka; // this line was missing
user.Gost = model.Gost;
user.PravoUnosa = model.PravoUnosa;
db.Entry(k).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}

TryUpdateModel(model, prefix, includeProperties) returns false but some properties are still updated

I have a scenario where I am editing a model in an ASP.NET MVC5 application and when I submit blank values TryUpdateModel returns false (correctly) but when I return the view with the same model that was passed into TryUpdateModel one of the properties has been updated but others havent' - even though they are all invalid.
Repro:
Load /Machines/Edit?serialNumber=2
Clear Position and Name fields (manually using delete, backspace, or cut)
Click Update button to submit form
The Name property is
updated even though TryUpdateModel returns false.
Is this a string only thing because I don't have a problem with the MachinePosition property being updated no matter what order I provide the includedProperties for https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.118).aspx#Anchor_12 in. Has anyone else come across this - it feels like I'm doing something wrong in my code because a side effect like this would surely be documented.
The only reason I noticed this was because I was returning to the main list of machines after attempting to do an invalid update and the noticed that the Name property was being updated for these machines yet when I debugged the code and stepped through it I wasn't hitting when the backing list was being updated/set... very confused.
My model:
public class Machine
{
[Required]
[Range(0, long.MaxValue)]
[Display(Name = "Serial")]
public long SerialNumber { get; set; }
[Required]
[Range(0, 1000)]
[Display(Name = "Position")]
public int MachinePosition { get; set; } = 0;
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
}
My view:
#model MyWebApplication.Machine
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Update #Model.Name</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<!-- Have the serial number shown in a hidden field so that it will be passed through on submit -->
#Html.HiddenFor(model => model.SerialNumber)
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.SerialNumber, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MachinePosition, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MachinePosition, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MachinePosition, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
</div>
}
My controller:
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditMachine(long? serialNumber)
{
if (serialNumber == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Get by serial
Machine machineToUpdate = MachineRepository.Get(serialNumber.Value);
string failureMessage = $"Model validation failed.";
// Model state is valid at this point because we have the serial set
if (ModelState.IsValid)
{
string oldName = machineToUpdate.Name;
int oldPosition = machineToUpdate.MachinePosition;
if (TryUpdateModel(machineToUpdate, "", new string[] { "Name", "MachinePosition" }))
{
Result result = MachineRepository.UpdateMachine(machineToUpdate);
if (result.ResultCode == ResultTypeEnum.Success)
{
// Update the list used by the view to include the new entry
RestoreDatabaseBackup();
// Use PRG pattern to prevent resubmit on page refresh
return RedirectToAction("Edit", new { serialNumber = serialNumber.Value, machineName = $"{oldName}/{machineToUpdate.Name}" });
}
failureMessage = $"There was an error updating the machine: {result.ResultMessage}";
}
}
// Set failure message
ViewBag.UpdateResultMessage = failureMessage;
ViewBag.UpdateSucceeded = false;
// When I get to here the "Name" field has been overwritten with a blank value
return View(machineToUpdate);
}

ModelState.IsValid does not update once I change input fields to valid inputs

I have a form "MovieForm" for adding movies to database. When I fill out all required inputs and press save button, movie gets added normally to database. If I first leave one or more required inputs empty and then press save, I get DataAnnotations error messages, "ModelState.isValid" becomes false and redirects me the same form which I'm already at with this code:
[HttpPost]
public ActionResult Save(Movie movie)
{
if (!ModelState.IsValid)
{
return View("MovieForm");
}
//logic for saving movie
}
and that's how it should be done. The problems occurs after this operation. Now, when I fill all the required inputs and press save button again, ModelState.IsValid didn't update and it's still false, so I get stuck in this if statement.
How can I reset it, so it checks again are requirements met?
Model:
public class Movie
{
[Key]
public Guid MovieID { get; set; }
[Required]
[StringLength(40)]
public string Title { get; set; }
[Required]
[StringLength(60)]
public string Director { get; set; }
[Required]
[StringLength(256)]
public string Actors { get; set; }
}
View
#using Cinema.Models
#model Cinema.Models.Movie
#using (Html.BeginForm("Save", "Movies", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="form-group">
#Html.LabelFor(m => m.Title, "Title", new { #class = "col-md-2 control-label" })
<div class="col-md-8">
#Html.TextBoxFor(m => m.Title, new { #class = "form-control col-md-4" })
#Html.ValidationMessageFor(m => m.Title, "", new { #class = "text-danger col-md-4 form-control-static" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Director, "Director", new { #class = "col-md-2 control-label" })
<div class="col-md-8">
#Html.TextBoxFor(m => m.Director, new { #class = "form-control col-md-4" })
#Html.ValidationMessageFor(m => m.Director, "", new { #class = "text-danger col-md-4 form-control-static" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Actors, "Actors ", new { #class = "col-md-2 control-label" })
<div class="col-md-8">
#Html.TextBoxFor(m => m.Actors, new { #class = "form-control col-md-4" })
#Html.ValidationMessageFor(m => m.Actors, "", new { #class = "text-danger col-md-4 form-control-static" })
</div>
</div>
#Html.HiddenFor(m => m.MovieID)
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<input type="submit" class="btn btn-default" value="Save" />
<a class="col-md-offset-1" href="/Movies/">cancel</a>
</div>
</div>
}
You can check error in ModelState object by expanding it in debug mode
Stephen's suggestion in his comment gives a very nice succinct way of filtering the ModelState to see what is causing errors. I did something similar (though rather longer winded) to combine them in a single string for easy viewing/copying/pasting. Try adding this to your controller:
string modelErrors = GetModelStateErrors(ModelState);
That calls this method:
public string GetModelStateErrors(ModelStateDictionary ms)
{
StringBuilder errors = new StringBuilder();
foreach (string k in ms.Keys)
{
if (ms[k].Errors.Count > 0)
{
errors.Append($"\n{k}:\n");
foreach (var e in ms[k].Errors)
{
errors.Append($" {e.ErrorMessage}\n");
}
}
}
return errors.ToString();
}

Posted ViewModel is always NULL

My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?
public class PaintballWorkerCreateViewModel
{
public PaintballWorker PaintballWorker { get; set; }
public PaintballWorkerHourlyRate HourlyRate { get; set; }
}
Controller
public ActionResult Create()
{
PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
{
PaintballWorker = new PaintballWorker(),
HourlyRate = new PaintballWorkerHourlyRate()
{
Date = DateTime.Now
}
};
return View(model);
}
[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
(...)
}
View, even added HiddenFor IDs (which aren't created in GET function in controller).
#model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel
#{
ViewBag.Title = "Utwórz pracownika";
Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}
<h2>Dodawanie pracownika</h2>
#using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PaintballWorker.Active)
#Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
#Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
#Html.HiddenFor(model => model.HourlyRate.Date)
#Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
#Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)
<div class="form-group">
#Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { #class = "control-label col-md-2" })
(...)
<div class="form-group">
#Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { #class = "form-control", #type = "number", #min = "0.1", #step = "0.1", #value = "10" } })
#Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj pracownika" class="btn btn-primary" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Powrót do listy", "Index", new object { }, new { #class = "btn btn-default" })
</div>
Your code looks fine.. looks like it's reference is being lost somewhere.. have you tried to remove the [PreventSpam(DelayRequest = 20)] attribute? So your controller would be like this:
public ActionResult Create()
{
PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
{
PaintballWorker = new PaintballWorker(),
HourlyRate = new PaintballWorkerHourlyRate()
{
Date = DateTime.Now
}
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
(...)
}
You are not posting the form correctly. Since the attributes are hidden, they are null by default.
After posting your controller does not see anything since the elements are hidden. Therefore it is null.
Use the extension method #Html.TextboxFor instead. Mvc viewengine will render the textbox and then you can put some values and post them.
you also need to make sure that you have mapped the route correctly in your code.
your problem may be because of naming conflict, that is the parameter name of the post action may not be the same as the property name in your viewmodel
Kindly follow the below link:
https://forums.asp.net/t/1670962.aspx?ViewModel+in+post+action+is+null
In that it specified solution and route cause for the problem clearly.
Note : I also had the same problem long back and solved it in the same way as mentioned. Hope it will be useful for you too
thanks
Karthik

Categories