MVC 3 HTML validation message - asp.net

When all property validation passes but the login info passed in is incorrect, I want to display a model-level error that reads:
Incorrect login. Reset Password.
#Html.ValidationSummary() is encoding the html.
I have tried creating a custom HtmlHelper for this but it's still doing the same thing.
I've also checked the source code and the ValidationSummary method uses internal methods that I can't use to recreate a helper for this.
Is there a way, whether in my view or in a HtmlHelper, to write an Html message if there is a model-level error?

I will use TempData to solve your problem.
In your method you set the message in
TempData["Error"] = "my error link";
then from your view you check if TempData["Error"] is not empty and then with
#Html.Raw(TempData["Error"])
you should get your message not encoded

Related

Spring MVC retain error meesage after redirect

I have a jsp with 2 input boxes that searches on 2 different scenarios. So , i have two different Get requests mapping to /search1 and /search2 but have created only one POJO for this.
As soon as user submits a search, I check if there is any results for that, and if not i add error message in model and "redirect:"(redirection because if i simply return a page and now make a new search the url will be /search1/search2) to the same basic page.
But everytime i load the page the error message persists.
Any workaround for this? how do i display the messaeg only on search.
Use Flash Attributes.
http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/
Add RedirectAttributes parameter to your controller's handler method.
then redirectAttributes.addFlashAttribute("modelAttributeName", "value");
then redirect
The controller handler that you redirect to should have "modelAttributeName" model attribute available to it.
Essentially your a putting a value into session which is removed as soon as it is read on the next request.
Another solution would be
you can use request parameter to pass message id and write utility to read message from properties file using message id in the get request of redirected controller.
Controller 1
return "redirect:your_redirection_url?messageId=1";
Controller 2 (where redirected)
if (messageid != null && !(messageid.equals(""))) { MessageUtility.addMessage(Integer.parseInt(messageid), model, locale); }

ErrorBinding Spring portlet MVC

Disclaimer: I wished I had a through understanding before starting working with the framework.
But as it is of now, I'm lacking on that front, and hence the question.
I am working with Spring-Portlet MVC.
I have a flow, where in I take an input on a screen, validate the input, depending upon its result it either render same screen or next screen.
Implementation detail:
I have an action method which takes form backed command object. It checks whether entered input is valid or not. If it is not valid, it populate error message in BindingResult instance it takes as another argument.
We have different render method, to render different screen.
I'm taking command object as an argument in these render method. This command object I'm receiving is same as one passed to action.
Problem:
While rerendering a screen spring-mvc should bind the error message populated in action method. Currently when I take command object as argument in render method spring-mvc is somehow unable to bind that error message. But interesting enough it is able to bind the error message if I don't take command object as argument in render method and rather create a new command object altogether there.
can,some one having better understanding of spring-portlet mvc please explain this behaviour, or tell where I am lacking in understanding.
Regards,
Mawia
EDIT: Just to enrich the below answer: Though I didn't exactly isolated the issue which was causing the said behaviour, but the way I met my requirement was using modelattribute. ModelAttribute can be used either on method or a parameter to a method. It ensures that model will made available to all the call till the view is render(that is my understanding!). So we don't need to take command object as parameter in Render method, just annotate the commandObject parameter in action method with ModelAttribute and then you can get the same object returned from model as suggested in the answer below.
I don't think the command/model object should be an argument/parameter in the render method. I have had the same issue trying to get the validation error messages when command/model is defined as argument in render method signature. I typically have the command/object creation/populate in a separate method, like this:
#ModelAttribute(value="address")
public Address getAddress(#RequestParam Integer id){
Address address = null;
if(id != null){
address = myService.getAddress(id);
}else{
address = new Address();
}
return address;
}
If I still need to access the ModelAttribute/command object from the render method, I typically get it by:
#RenderMapping
public String showAddressPage(ModelMap modelMap){
Address address = modelMap.get("address");
//make any additional changes to address
}
I used this example as reference article

Model Binding and Validation Errors

I am using asp.net MVC3 and I am very new to this technology.
My models are designed in such a way that the properties will throw validation errors if the data is invalid. In this case, the properties are not set with invalid data.
When I redisplay my editing-view, validation error messages are shown; however the values that the user previously entered are gone because the model that it is bound to only contains the old-valid data.
For example, say I had a Person class and the Name property cannot be a null or empty string otherwise it throws a validation exception and prevents the property from being set. Now say the user removes the value from the Name property and tries to save the Person from the web. A validation exception will be thrown and handled properly to add the error to the ModelState so that it is displayed on the screen; however the old value for the Name is redisplayed since the invalid, empty string never made it into the property.
I do not know how to solve this problem and any advice on the issue would be greatly appreciated.
My advise is allow invalid data but use validation attributes. You wont save invalid entities so there is no problem and this is the standard approach these days. If you don't want do that, there is no easy solution. Most simple solution would be using the info from Request.Form
You should implement IValidatableObject to performe this kind of validation at server side.
From MSDN IValidatableObject Interface:
Provides a way for an object to be invalidated.
Theres an exemple here Using IValidatableObject Custom Validation, also from MSDN.
The solution to this problem was to create a ViewModel that allowed invalid data to be entered into this. This solution also simplified my ModelBinder classes because it took on most of the work.

Displaying detailed error messages other than that what is defined in Fluent Validation

I am using ASP.NET MVC 4 and the latest version of Fluent Validation. I am using Fluent Validation over data annotations.
I am looking at adding a validation error summary to my view where data is to be entered. I currently just use the ValidationMessageFor with each input field. Sometimes I need to do other validation (like against a service) after the form validation is true, and then have these messages displayed on the view if the validation failed. And because this validation is not related to any input field I want to have this error displayed in a validation error summary.
Lets take for example my employee number field, it is required and it cannot be longer than 10 characters. I have the following validator class using Fluent Validation:
public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>
{
public CreateEmployeeViewModelValidator()
{
RuleFor(x => x.EmployeeNumber)
.NotEmpty()
.WithMessage("Required")
.Length(1, 10)
.WithMessage("Must not be greater than 10 characters");
}
}
My HTML markup:
#Html.TextBoxFor(x => x.EmployeeNumber)
#Html.ValidationMessageFor(x => x.EmployeeNumber)
This part works fine. If the textbox is empty then it displays the "Required" error message next to the textbox, and if it is more than 10 characters then it displays the "Must not be greater than 10 characters" error message.
Now I want to add my validation error summary to the view. I added the following:
#Html.ValidationSummary(true, "Errors have occurred while. Fix the errors before saving.")
I would like it to display some decent error message relating to the control above. Although it displays "Required" next to the employee number if it is empty, I would like it to display something like "Employee number is required" in the validation error summary. Currently it just displays the text "Errors have occurred while. Fix the errors before saving.".
And when I need to do other validation after form validation is true, like check if the employee is a valid employee, then I also want this error message to be displayed. If I have this in my controller's action method:
ModelState.AddModelError("", "My test error message");
I would like to have "My test error message" to be displayed in the validation error summary.
How would something like this be possible?
This is how you should set it up
#Html.ValidationSummary(false)
Say you don't validate on the client-side or validation there fails, when your form is submitted you have those errors available in your controller. You can then add more errors just as you are adding it now:
ModelState.AddModelError("", "My test error message");
When the view is rendered back to your client it will contain the error message from your model's properties plus the custom messages.
UPDATE:
Brendan mentioned that he wants to show a short message besides each of the erring control as well as to provide a longer version of the error message for the same erring control, and show that longer version of the error message in the ValidationSummary. It can be done with a bit of a hack.
Suppose the model has a property called EmployeeNumber as is shown in the question. The form is submitted back and it is validated on the server side using the custom validator setup by Brendan. All is good. Now we can use reflection and inspect the model's properties and find if an error exist in the modelstate dictionary, use the property name and look it up in some error collection object (could be a resource file or a database, all the same approach).
[HttpPost]
public ActionResult AcceptEmployee(EmployeeModel model)
{
// customErrors here is a dictionary
// that contains information for the custom message
// i.e. Key="EmployeeNumber", Message="Employee number is required"
// like I've mentioned this can be a query from the database
// or a get from a resource file
// for the sake of this example, I used a dictionary
foreach (var property in model.GetType().GetProperties())
{
if (ModelState[property.Name] !=null
&& ModelState[property.Name].Errors.Any())
{
ModelState.AddModelError("", customErrors[property.Name]);
}
}
}
Now make sure you exclude property errors from the summary by doing:
#Html.ValidationSummary(true)
So now you can enjoy having a short error besides an erring control and a (very) long error message in a summary.
#Html.ValidationSummary(true) -->Correct
Will not display default error messages all together.
You will be able to display custom messages by just writing the below statement
ModelState.AddModelError("", "This account is not registered in our system.");
All the annotation messages defined in the class will be displayed right next to the controls neatly.

Custom Membership Provider and ChangePassword control

I have implemented a Custom Membership provider for my existing database schema with the help of the following link
I have overridden the following methods CreateUSer, ValidateUser, GetUser, ChangePassword and ResetPassword.
For the ChangePassword method , it validates the new password for the Minimum length and also for the Number of Alphanumeric characters. If the validation fails the method throws an Argument Exception with the exact error.
The problem what I face is, I am using the built in Change password control, I get the following error, "Argumnet exception was unhandled in user code" .
Also it displays a generic error
"Password incorrect or New Password invalid."
I would rather want to display the exact reason of the error why the password validation failed.
How do i go abou implementhing this. I would appreciate any help or guidance.
Thanks
The problem is likley in your implementation the virtual function MembershipUser.ChangePassword From the MSDN article, it needs to take 2 parameters:
oldPassword
Type:System.String
The current password for the membership user.
newPassword
Type:System.String
The new password for the membership user.
Without seeing you ChangePassword function, I would guess that you are
Not passing the "oldPassword" argument, or
Passing a value that's not a string as one of those 2 arguments.
Edit: Based on your comment, what you really want to do is handle the ChangePasswordError event of the ChangePassword control. This will let you provide custom feedback when an error is raised.
I'm having the same issue. It appears you'll have to use a regular form and create error handling to display the message you would like instead of the built in message that appears.

Resources