0

I'm following this article

http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs

to include a Service Layer with Business Logic in my ASP.NET MVC Web Application.

I'm able to pass messages from the Service Layer to the View Model in a Html.ValidationSummary using ModelState class.

I perform basic validation logic on the View Model (using DataAnnotation attributes) and I have ClientValidation enabled by default, which displaying the error message on every single field of my form.

The Business logic error message which come from the Service Layer are being displayed on Html.ValidationSummary only after Posting the form to the Server.

After Validation from the Service Layer, I would like highlight one or more fields and have the message from the Service Layer showing on these fields instead that the Html.ValidationSummary.

Any idea how to do it?

2 Answers 2

2

Here's how the validation looks on the server:

protected bool ValidateProduct(Product productToValidate)
{
    if (string.IsNullOrEmpty(productToValidate.Name))
        _validatonDictionary.AddError("Name", "Name is required.");
    if (string.IsNullOrEmpty(productToValidate.Description))
        _validatonDictionary.AddError("Description", "Description is required.");
    if (productToValidate.UnitsInStock < 0)
        _validatonDictionary.AddError("UnitsInStock", "Units in stock cannot be less than zero.");
    return _validatonDictionary.IsValid;
}

All you have to do is to have corresponding ValidationMessageFor helpers for those fields in the view and the error message coming from the server will be associated to the corresponding field:

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
        @Html.ValidationMessageFor(x => x.Name)
    </div>
    <div>
        @Html.LabelFor(x => x.Description)
        @Html.EditorFor(x => x.Description)
        @Html.ValidationMessageFor(x => x.Description)
    </div>
    <button type="submit">Create</button>
}
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks to Darin I found out the solution to my problems.

In details:

I can use

 _validatonDictionary.AddError("Name of my field", "Custom message")

so I can show a message and highlight that specific field (very simple to do with DataAnnotation).

In case I want display just a message in ValidationSummary without highlight a specific field I use

_validatonDictionary.AddError(string.Empty, "Custom message")

Please note the string.Empty

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.