HelpersMaison.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. namespace AppliWebANA.Helpers { // Ne pas oublier de faire le using de l'espace de nom si on veut voir les méthodes d'extention !
  9. public static class HelpersMaison {
  10. public static MvcHtmlString AllValidationMessagesTooltipFor<TModel, TProperty>(
  11. this HtmlHelper<TModel> hh,
  12. Expression<Func<TModel, TProperty>> expression,
  13. object attributs = null ) {
  14. // La propriété en erreur ?
  15. string nomPropriete = ModelMetadata.FromLambdaExpression( expression, hh.ViewData ).PropertyName;
  16. ModelState modelStatePourLaPropriete = null;
  17. hh.ViewData.ModelState.TryGetValue( nomPropriete, out modelStatePourLaPropriete );
  18. // Pas d'erreur ?
  19. if( modelStatePourLaPropriete == null || modelStatePourLaPropriete.Errors.Count == 0 ) {
  20. return MvcHtmlString.Empty;
  21. }
  22. else {
  23. // Si erreurs
  24. IDictionary<string, object> dicoAttributsHtml = attributs as IDictionary<string, object>;
  25. if( dicoAttributsHtml == null )
  26. dicoAttributsHtml = HtmlHelper.AnonymousObjectToHtmlAttributes( attributs );
  27. // Récupérer le texte
  28. object innerHTML;
  29. if( !dicoAttributsHtml.TryGetValue( "innerHTML", out innerHTML ) )
  30. innerHTML = "*";
  31. // Récupérer le tooltip
  32. object titleDeBase;
  33. if( dicoAttributsHtml.TryGetValue( "title", out titleDeBase ) ) {
  34. titleDeBase = $"{titleDeBase}\n";
  35. }
  36. // Et y ajouter toutes les erreurs
  37. StringBuilder erreurs = new StringBuilder($"{titleDeBase}\n");
  38. foreach( var erreur in modelStatePourLaPropriete.Errors )
  39. erreurs.AppendLine( erreur.ErrorMessage );
  40. // Récupérer la classe CSS
  41. object classeCSSDeBase = null;
  42. if( dicoAttributsHtml.TryGetValue( "class", out classeCSSDeBase ) ) {
  43. classeCSSDeBase = $" {classeCSSDeBase}"; //string.Format( " {0}", classeCSSDeBase)
  44. }
  45. // Et y ajouter AllValidationMessagesTooltipFor
  46. // Fabriquer un <span class="....." title=".....">...</span>
  47. return new MvcHtmlString( $"<span class=\"AllValidationMessagesTooltipFor{classeCSSDeBase}\" title=\"{erreurs}\">{innerHTML}</span>" );
  48. }
  49. }
  50. }
  51. }