One property with a list of model errors in mvc c#

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?

Answers


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")
}

@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)

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

Strongly typed validation check .


Need Your Help

Getting lot of errors while building custom tab bar app with XCode 4.2

iphone objective-c ios ios5 xcode4.2

I just downloaded the new XCode and built my app which has a custom tab bar drawing included.

cocos2d-X facebook integration c++

android c++ facebook cocos2d-x

I am a new developer to the cocos2d-X platform using c++. I am looking to integrate Facebook sdk into my game. Is the only way of doing this through, ANDROID JNI bridge. Is there any native C++ apis