| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text;
- using System.Web;
- using System.Web.Mvc;
- namespace AppliWebANA.Helpers { // Ne pas oublier de faire le using de l'espace de nom si on veut voir les méthodes d'extention !
- public static class HelpersMaison {
- public static MvcHtmlString AllValidationMessagesTooltipFor<TModel, TProperty>(
- this HtmlHelper<TModel> hh,
- Expression<Func<TModel, TProperty>> expression,
- object attributs = null ) {
- // La propriété en erreur ?
- string nomPropriete = ModelMetadata.FromLambdaExpression( expression, hh.ViewData ).PropertyName;
- ModelState modelStatePourLaPropriete = null;
- hh.ViewData.ModelState.TryGetValue( nomPropriete, out modelStatePourLaPropriete );
- // Pas d'erreur ?
- if( modelStatePourLaPropriete == null || modelStatePourLaPropriete.Errors.Count == 0 ) {
- return MvcHtmlString.Empty;
- }
- else {
- // Si erreurs
- IDictionary<string, object> dicoAttributsHtml = attributs as IDictionary<string, object>;
- if( dicoAttributsHtml == null )
- dicoAttributsHtml = HtmlHelper.AnonymousObjectToHtmlAttributes( attributs );
- // Récupérer le texte
- object innerHTML;
- if( !dicoAttributsHtml.TryGetValue( "innerHTML", out innerHTML ) )
- innerHTML = "*";
- // Récupérer le tooltip
- object titleDeBase;
- if( dicoAttributsHtml.TryGetValue( "title", out titleDeBase ) ) {
- titleDeBase = $"{titleDeBase}\n";
- }
- // Et y ajouter toutes les erreurs
- StringBuilder erreurs = new StringBuilder($"{titleDeBase}\n");
- foreach( var erreur in modelStatePourLaPropriete.Errors )
- erreurs.AppendLine( erreur.ErrorMessage );
- // Récupérer la classe CSS
- object classeCSSDeBase = null;
- if( dicoAttributsHtml.TryGetValue( "class", out classeCSSDeBase ) ) {
- classeCSSDeBase = $" {classeCSSDeBase}"; //string.Format( " {0}", classeCSSDeBase)
- }
- // Et y ajouter AllValidationMessagesTooltipFor
- // Fabriquer un <span class="....." title=".....">...</span>
- return new MvcHtmlString( $"<span class=\"AllValidationMessagesTooltipFor{classeCSSDeBase}\" title=\"{erreurs}\">{innerHTML}</span>" );
- }
- }
- }
- }
|