2

In my controller which is having a list (atmost 3) error messages related to password check will be stored in the property named Password.

IEnumerable<PasswordMessages> passwordMessage = LoanTrackerServices.CheckPasswordRequirements(model.NewPassword, model.EmailId);
if ( passwordMessage.Count() > 0 )
{
    foreach (PasswordMessages pm in passwordMessage)
    {
        ModelState.AddModelError("Password",( pm.Message));
    }
    LoginPageModel loginModel = new LoginPageModel();
    return View("Index", new HomePageModel() { Register = model, Login = loginModel });
}

But in my view i am unable to figure out how to get all those (atmost 3) error messages. Right now only the first message with in the list is displaying. here is my code in view

for (int i = 0; i < ViewData.ModelState["Password"].Errors.Count; i++)
{
     @Html.ValidationMessage("Password")
}

How to get all those error messages which are stored with in the Password?

3 Answers 3

5

You just need a summary instead of a message:

@Html.ValidationSummary("Password")

So get rid of this:

for (int i = 0; i < ViewData.ModelState["Password"].Errors.Count; i++)
{
    @Html.ValidationMessage("Password")
}
Sign up to request clarification or add additional context in comments.

9 Comments

This one works. but it is displaying heading before the messages
@user2619542, you can modify the template. Just look at the HTML/CSS that's rendered and target the rendered tags. To get rid of the heading, target the tag and set display: none.
I used the style display:none, then it is not at all displaying the error messages. I want those error messages just without the heading message
@user2619542, if you target the right element it won't hide the entire set of messages; your CSS is just wrong. Target the heading, the element you want to get rid of, specifically.
these are the styles in CSS .validation-summary-errors { font-weight: bold; color: #ff0000; display:none; } .validation-summary-valid { display: none; } i added display:non for validation-summary-errors class
|
1
@Html.ValidationSummary()

Will show all Model errors in one place what isn't desirable for the most cases.

I've written a helper method which will let you show only errors for specific field: https://gist.github.com/DimaSalakhov/8548393. It's based on standart ValidationMessageFor<>().

Add it to your project, referrence on a View and use as follows:

@Html.ValidationSummaryFor(x => x.Password)

Comments

0
@if(ViewData.ModelState.IsValidField(nameof(Model.Property)))
{
     // show some thing
}
else
{
     // show some thing else
}

Strongly typed validation check .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.