Search code examples
asp.net-mvcvalidationmodel-view-controllerservice-layer

ASP.NET MVC client validation from Service Layer


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?


Solution

  • 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>
    }