// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.AspNetCore.Mvc.ViewFeatures { /// /// Contract for a service providing validation attributes for expressions. /// public abstract class ValidationHtmlAttributeProvider { /// /// Adds validation-related HTML attributes to the if client validation is /// enabled. /// /// A instance for the current scope. /// The for an expression. /// /// The to receive the validation attributes. Maps the validation /// attribute names to their values. Values must be HTML encoded before they are written /// to an HTML document or response. /// /// /// Adds nothing to if client-side validation is disabled. /// public abstract void AddValidationAttributes( ViewContext viewContext, ModelExplorer modelExplorer, IDictionary attributes); /// /// Adds validation-related HTML attributes to the if client validation is /// enabled and validation attributes have not yet been added for this in the /// current <form>. /// /// A instance for the current scope. /// The for the . /// Expression name, relative to the current model. /// /// The to receive the validation attributes. Maps the validation /// attribute names to their values. Values must be HTML encoded before they are written /// to an HTML document or response. /// /// /// Tracks the in the current to avoid generating /// duplicate validation attributes. That is, validation attributes are added only if no previous call has /// added them for a field with this name in the <form>. /// public virtual void AddAndTrackValidationAttributes( ViewContext viewContext, ModelExplorer modelExplorer, string expression, IDictionary attributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (modelExplorer == null) { throw new ArgumentNullException(nameof(modelExplorer)); } if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } // Don't track fields when client-side validation is disabled. var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null; if (formContext == null) { return; } var fullName = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression); if (formContext.RenderedField(fullName)) { return; } formContext.RenderedField(fullName, true); AddValidationAttributes(viewContext, modelExplorer, attributes); } } }