ASP.NET MVC: Validation messages set in TryUpdateModel not showning ValidationSummary - c#

I've been trying to follow the validation tutorials and examples on the web, such as from David Hayden's Blog and the official ASP.Net MVC Tutorials, but I can't get the below code to display the actual validation errors. If I have a view that looks something like this:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Parent>" %>
<%-- ... content stuff ... --%>
<%= Html.ValidationSummary("Edit was unsuccessful. Correct errors and retry.") %>
<% using (Html.BeginForm()) {%>
<%-- ... "Parent" editor form stuff... --%>
<p>
<label for="Age">Age:</label>
<%= Html.TextBox("Age", Model.Age)%>
<%= Html.ValidationMessage("Age", "*")%>
</p>
<%-- etc... --%>
For a model class that looks like this:
public class Parent
{
public String FirstName { get; set; }
public String LastName { get; set; }
public int Age { get; set; }
public int Id { get; set; }
}
Whenever I enter an invalid Age (since Age is declared as an int), such as "xxx" (non-integer), the view does correctly display the message "Edit was unsuccessful. Correct errors and retry" at the top of the screen, as well as highlighting the Age text box and put a red asterisk next to it, indicating the error. However, no list of error messages is displayed with the ValidationSummary. When I do my own validation (e.g.: for LastName below), the message displays correctly, but the built-in validation of TryUpdateModel does not seem to display a message when a field has an illegal value.
Here is the action invoked in my controller code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditParent(int id, FormCollection collection)
{
// Get an updated version of the Parent from the repository:
Parent currentParent = theParentService.Read(id);
// Exclude database "Id" from the update:
TryUpdateModel(currentParent, null, null, new string[]{"Id"});
if (String.IsNullOrEmpty(currentParent.LastName))
ModelState.AddModelError("LastName", "Last name can't be empty.");
if (!ModelState.IsValid)
return View(currentParent);
theParentService.Update(currentParent);
return View(currentParent);
}
What did I miss?

I downloaded and looked at the ASP.NET MVC v1.0 source code from Microsoft, and discovered that, either by accident or by design, there isn't a way to do what I want to do, at least by default. Apparently during a call to UpdateModel or TryUpdateModel, if validation of an integer (for example) fails, an ErrorMessage is not explicitly set in the ModelError associated with the ModelState for the bad value, but instead the Exception property is set. According to the code from the MVC ValidationExtensions, the following code is used to fetch the error text:
string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
Notice the null parameter for the modelState is passed. The GetUserErrorMEssageOrDefault method then begins like this:
private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) {
if (!String.IsNullOrEmpty(error.ErrorMessage)) {
return error.ErrorMessage;
}
if (modelState == null) {
return null;
}
// Remaining code to fetch displayed string value...
}
So, if the ModelError.ErrorMessage property is empty (which I verified that it is when trying to set a non-integer value to a declared int), MVC goes on to check the ModelState, which we already discovered is null, thus null is returned for any Exception ModelError. So, at this point, my 2 best work-around ideas to this issue are:
Create a custom Validation extension that correctly returns an appropriate message when ErrorMessage is not set, but Exception is set.
Create a pre-processing function that is called in the controller if ModelState.IsValid returns false. The pre-processing function would look for values in the ModelState where the ErrorMessage is not set, but the Exception is set, and then derive an appropriate message using the ModelState.Value.AttemptedValue.
Any other ideas?

Related

MVC Foolproof Validation RequiredIfFalse returning error incorrectly

I'm using the MVC Foolproof Validation library to make dependent requirements:
public bool IsRequired { get; set; }
[RequiredIfTrue("IsRequired", ErrorMessage = "This field is required")]
public int RequiredIfTrueSelectID { get; set; }
This works perfectly on the client side, allowing me to submit the form without a RequiredIfTrueSelectID value (i.e. value is 0), but on the [HttpPost] the ModelState.IsValid returns false, and with the following result in the immediate window:
myViewModel.IsRequired
true
ModelState["RequiredIfTrueSelectID"].Errors[0]
{System.Web.Mvc.ModelError}
ErrorMessage: "A value is required."
Exception: null
I'm ensuring that I'm posting back the value of RequiredIfTrueSelectID (as you can see in the first immediate window query above). Why am I getting the "A value is required" message, and how can I suppress this error?
By the way, I'm in MVC5. Maybe the ModelState implementation has changed since Foolproof's last update 2 years ago? Does anyone else know of a more recently-published library that functions like Foolproof?
Controller method:
[HttpPost]
public virtual ActionResult ValidationTest(TestViewModel vm)
{ //breakpoint here to check ModelState.IsValid
return View(vm);
}
Oh, duh. Your field is a value type.
Value types are always required. You need to make the type nullable if you want it to be optional.
Notice that the error message is not the same as the error message used in your validator, that's the first clue.

MVC 5 Remote Validation

I need to validate an input field value from user before the form is submitted.
I have created an action in my custom controller and decorated the field with it:
action name: CheckValue
controller name: Validate
[Remote("CheckValue", "Validate"), ErrorMessage="Value is not valid"]
public string Value { get; set; }
The problem is when I press submit, the form is being submitted and then the message Value is not valid is shown if the value entered by the user is not valid.
How can I validate the value entered by user and prevent the form to be submitted if value is not valid, and display the error message?
If I try in JavaScript to check if the form is valid $("#formId").valid() that returns true, that means no matter what is the status of the value (valid or not) the form is valid.
In the other hand if I decorate another field with the [Required] attribute the form is not submitted and the error is shown for that field that is required. However the validation doesn't occur behind the scene for the remote validation field.
The complete solution of Remote Validation in MVC. It will check if the email exists in database and show the following error:
Email already exists
Account Controller Action
[AllowAnonymous]
[HttpPost]
public ActionResult CheckExistingEmail(string Email)
{
try
{
return Json(!IsEmailExists(Email));
}
catch (Exception ex)
{
return Json(false);
}
}
private bool IsEmailExists(string email)
=> UserManager.FindByEmail(email) != null;
Add Model Validation
[Required]
[MaxLength(50)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[System.Web.Mvc.Remote("CheckExistingEmail", "Account", HttpMethod = "POST", ErrorMessage = "Email already exists")]
public string Email { get; set; }
Add Scripts
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
You dont put the Controller code. But must to be something like this:
Your code:
[Remote("CheckValue", "Validate", ErrorMessage="Value is not valid")]
public string Value { get; set; }
My code for the controller(Validate):
public ActionResult CheckValue(string Value)
{
if (Value == "x value")
{
// This show the error message of validation and stop the submit of the form
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
// This will ignore the validation and the submit of the form is gone to take place.
return Json(false, JsonRequestBehavior.AllowGet);
}
}
With the reference of c-sharpcorner demo
We can use RemoteAttribute.
Step 1
In the HomeController create a method and for that write the following.
public JsonResult IsUserExists(string UserName)
{
//check if any of the UserName matches the UserName specified in the Parameter using the ANY extension method.
return Json(!db.Users.Any(x => x.UserName == UserName) ,JsonRequestBehavior.AllowGet);
}
You might be wondering why we are returning JsonResult back. We want the validation to occur at the client side, so we are returning a JsonResult.
Step 2
The next step is to hook this method up with the username property and for that first we need to add a class file in the models folder, add a partial User class and provide the required customization to the UserName property.
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace UniqueField.Models
{
[MetadataType(typeof(UserMetaData))]
public partial class User
{
}
class UserMetaData
{
[Remote("IsUserExists","Home",ErrorMessage="User Name already in use")]
public string UserName { get; set; }
}
}
Step 3
In create.cshtml we need to specify the source of the three jQuery files in the given order.
<h2>Create</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
The existing answers are great but there are a couple of gotchas:
1) The validation method's parameter name has to exactly match the name of the property being validated, e.g. for
[System.Web.Mvc.Remote("CheckExistingDocumentTypeCode", "DocumentTypes", HttpMethod = "POST", ErrorMessage = "Code already exists")]
public string DocumentTypeCode { get; set; }
The validation method's parameter must be called DocumentTypeCode, including the capital letter, or else you'll get a null as the parameter instead of the value of the property being validated:
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> CheckExistingDocumentTypeCode(string DocumentTypeCode)
Be particularly wary of this if you are a Resharper user, of if you're writing multipurpose validation methods for use by more than one property.
2) I had to get this working with a Telerik grid and I had to implement it slightly differently in order to get the validation failure messages to show correctly in the grid (the examples here showed 'false' as the validation error message):
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> CheckExistingDocumentTypeCode(string DocumentTypeCode)
{
try
{
if (!await IsDocTypeCodeExists(DocumentTypeCode))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("This Document Type Code is already in use", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
Remote Validation in MVC
Model Class must have a namespace "System.Web.Mvc" where you have defined the property.
using System.Web.Mvc;
[Required(ErrorMessage = "E-mail is required")]
[RegularExpression(#"^[a-zA-Z0-9_\.-]+#([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Email is not valid")]
[StringLength(30, ErrorMessage = "Email must not be more than 30 char")]
[Remote("IsEmailAvailable", "User", ErrorMessage = "E-mail already in use")]
public string Email { get; set; }
Make sure you have to implement IsEmailAvailable Action on the Controller.
[HttpGet]
public JsonResult IsEmailAvailable(string email)
{
// Check if the e-mail already exists
return Json(!db.Users.Any(x => x.Email == email), JsonRequestBehavior.AllowGet);
}
Make sure you have added this js on View for client-side validation.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
and also enable client-side validation from web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Note:
Remote attribute only works when JavaScript is enabled. If the end-user, disables JavaScript on his/her machine then the validation does not work. This is because RemoteAttribute requires JavaScript to make an asynchronous AJAX call to the server-side validation method. As a result, the user will be able to submit the form, bypassing the validation in place. This why it is always important to have server-side validation.
In case when Javascript is disabled:
To make server-side validation work, when JavaScript is disabled, there are 2 ways
Add model validation error dynamically in the controller action
method.
Create a custom remote attribute and override IsValid() method.
Adding model validation error dynamically in the controller action method. Modify the Create action method that is decorated with [HttpPost] attribute as shown below.
[HttpPost]
public ActionResult Create(User user)
{
// Check if the Email already exists, and if it does, add Model validation error
if (db.Users.Any(x => x.Email == user.Email))
{
ModelState.AddModelError("Email", "Email already in use");
}
if (ModelState.IsValid)
{
db.Users.AddObject(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
At this point, disable JavaScript in the browser, and test your application. Notice that, we don't get client-side validation, but when you submit the form, server-side validation still prevents the user from submitting the form, if there are validation errors.
However, delegating the responsibility of performing validation, to a controller action method violates the separation of concerns within MVC. Ideally, all validation logic should be in the Model. Using validation attributes in MVC models should be the preferred method for validation.
I got the same problem i was copying and pasting script links >
problem solved when I drag and drop jquery files from script folder to view page
I hope this help.

Show validation message, but clear value

I've been searching around and I'm not able to find an answer on what seems like a simple requirement:
With MVC Data Annotation validation, can you show the validation message ('must be a string with a maximum length of 5') in the validation summary or next to field, but clear the value of the text box (when validation fails).
I've tried to use ModelState.Clear() and ModelState.Remove("CompanyName"), but this clears both the value and validation message (validation state).
I'm asking this because recently we had a penetration test and one of the recommendations was to not pre-populate secure values (credit card number etc) if validation fails. This is obviously a minor issue, but the recommendation was to not send the value back across the internet (from the server) if we didn't have to.
Here is the code I'm working with:
public ActionResult Edit()
{
return View();
}
[HttpPost]
public ActionResult Edit(CompanyInput input)
{
if (ModelState.IsValid)
{
return View("Success");
}
//ModelState.Clear // clears both the value and validation message
//ModelState.Remove("CompanyName") // same result
return View(new CompanyInput());
}
And the view model:
public class CompanyInput
{
[Required]
[StringLength(5)]
public string CompanyName { get; set; }
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
}
And the view:
#model Test.Models.CompanyInput
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Company"))
{
#Html.EditorForModel()
<button type="submit">Submit</button>
}
The ModelState of each field holds more than just the value, so removing it from the collection outright removed your error message as expected. I believe you should be able to clear just the value however, by doing something like.
ModelState["CompanyName"].Value = null;
EDIT: Upon closer inspection I found that the Value property is of type ValueProviderResult, simply nulling it doesn't give the desired result, and because the properties of this class appear to be getters only you have to replace the instance with your own. I've tested the following and it works for me.
ModelState["CompanyName"].Value = new ValueProviderResult(string.Empty, string.Empty, ModelState["CompanyName"].Value.Culture);
Because the ModelState isn't valid, you will either have to create a custom validator or a jQuery ajax/json call to determine if the data needs to be cleared or not.
Just changing the model property to string.Empty or something like that won't do the trick because the entire view gets re-rendered with the previous successful posted model but with the ModelState validation errors.
Yes you can add error message like this
[Required(ErrorMessage = "must be a string with a maximum length of 5")]
Update after clarity from OP:
To clear e.g. Input.Field = string.Empty;
You can create a custom validation class which is inherited from ValidationAttribute class
The following link gives a clear idea about how to implement custom validation class suitable for your problem.
Custom Data Annotation

Hidden form fields not appearing in MVC Model after post-back

I have a new MVC 4 Application with a fairly basic View/Controller. The associated Model contains a couple properties that I've mapped to Hidden form fields. When the Page renders the first time (e.g. via the HttpGet Action) it all looks fine. But when the form is Post'ed by selecting the Submit button the resulting Model presented to the Action no longer has the Hidden field values set. Here is a walkthrough of the particulars.
Here is a sample of the Model:
public class Application
{
public bool ShowSideBars { get; set; }
}
Here is the initial Controller *Action* (which seems to work fine):
[HttpGet]
public ActionResult Application()
{
var model = Request.ParseFromQueryString<Application>();
model.ShowSideBars = true;
return View(model);
}
This maps to the View as follows:
<fieldset>
#Html.HiddenFor(m => m.ShowSideBars)
...
</fieldset>
This results in the following mark-up to be rendered inside the fieldset:
<input data-val="true" data-val-required="The ShowSideBars field is required." id="ShowSideBars" name="ShowSideBars" type="hidden" value="True" />
Note: I sure wish I knew why MVC has decided to add the '... field is required' content when I didn't flag it as required, but that's for another question
Here is the Action that is called when the form is submitted. At this point the aforementioned property will no longer be set to 'true'.
[HttpPost]
public ActionResult Application(Application application)
{
// Other work done here
return View(application);
}
At present, there are no custom Model Binders. Also, I've tested some other data types and I'm seeing the same thing.
Can someone explain why hidden form values are not being returned? Am I just doing this all wrong?
If you have the property in your model decorated with a ReadOnlyAttribute the value will not be populated back into the model for you. After all, it is read only.
I just had the same problem. The form didn't submitted the hidden property because the model class didn't had a proper getter and setter for that property.
I know that is not the issue you had, just figured it might help other people that will lend in this page.
I cannot reproduce the issue (ASP.NET MVC 4 Beta running on VS 2010 .NET 4.0).
Model:
public class Application
{
public bool ShowSideBars { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Application()
{
var model = new Application();
model.ShowSideBars = true;
return View(model);
}
[HttpPost]
public ActionResult Application(Application application)
{
return Content(application.ShowSideBars.ToString());
}
}
View:
#model Application
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.ShowSideBars)
<button type="submit">OK</button>
}
When I submit the form, the model binder correctly assigns the ShowSideBars property in the POST action to true.
Note: I sure wish I knew why MVC has decided to add the '... field is
required' content when I didn't flag it as required, but that's for
another question
That's because non-nullable types such as booleans are always required. You could stop ASP.NET MVC helpers from emitting HTML5 data-* client side validation attributes for them by putting the following line in Application_Start:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
I think the fields MUST be within the form html tags for the hidden ones to be posted back and not ignored
try this:
public class Model
{
[ScaffoldColumn(false)]
public bool InvisibleProperty { get; set; }
}
more info here (ScaffoldColumn(bool value) vs HiddenInput(DisplayValue = bool value) in MVC)
In my case it was because I had declared a field instead of a property:
public BaseController.Modes Mode;
doesn't work. But:
public BaseController.Modes Mode { get; set; }
works. The default model binder only works with properties.
I kid you not, this is another reason it could happen.
My form had the same field in it twice. The other field was actually not in the form, but that doesn't matter.
Run this jQuery in the developer console to see how many elements come back:
$("[id$=PropertyName]"); // Search for ids ending with property name.
Example:
For me, in Core 6 the solution was removing [Editable(false)] attribute from the model class Id property which I wanted to tunnel through get/post as a hidden form field. In .Net 4.8 it was not a problem.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

How to write a code for displaying the alert message: "Successfully registered", after user data is stored in database, using MVC
I am using Asp.Net MVC3, C#, Entity Model.
Try using TempData:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
#if (TempData["notice"] != null) {
<p>#TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.
Having said that it would be possible to trigger an alert from the controller code by doing something like this -
public ActionResult ActionName(PostBackData postbackdata)
{
//your DB code
return new JavascriptResult { Script = "alert('Successfully registered');" };
}
You can find further info in this question - How to display "Message box" using MVC3 controller
Personally I'd go with AJAX.
If you cannot switch to #Ajax... helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
#using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
#{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('#Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('#Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
#Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");

Categories