Search code examples
asp.net-mvcasp.net-mvc-4razormvc-editor-templates

ASP.NET MVC - How to use Required message inside a EditorTemplates


I have a simple model:

    public abstract class Person
    {
        [Required(ErrorMessage = "Il nome è obbligatorio!!!")]
        [UIHint("txtGeneric")]
        [Display(Name = "Nome")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Il cognome è obbligatorio!!!")]
        [UIHint("txtGeneric")]
        [Display(Name = "Cognome")]
        public string Surname { get; set; }

        [Required(ErrorMessage = "L'email è obbligatoria e deve essere in formato valido (nome@dominio.it)!!!")]
        [UIHint("txtEmail")]
        [Display(Name = "E-mail")]
        public string Email { get; set; }
}

I created inside the EditorTemplate the txtGeneric.cshtml file. It is like this:

@model string
<input name="@ViewData.TemplateInfo.HtmlFieldPrefix" id="@ViewData.TemplateInfo.HtmlFieldPrefix" data-validation="required" data-validation-error-msg="MESSAGE_TO_PUT" value="@Model" />

I want to know how to take the text associated Errormessage of Required attribute to put into my txtGeneric.cshtml file. How can I do that?

Thanks


Solution

  • This works:

     @{
         string requiredMsg = "";
         foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
         {
             if (attr.Key == "data-val-required") {
                 requiredMsg = attr.Value.ToString();
             }
         }
     }
    

    or this:

     @{
         string requiredMsg = "";
         IEnumerable<ModelClientValidationRule> clientRules = ModelValidatorProviders.Providers.GetValidators(ViewData.ModelMetadata, ViewContext).SelectMany(v => v.GetClientValidationRules());
         foreach (ModelClientValidationRule rule in clientRules)
         {
             if (rule.ValidationType == "required")
             {
                 requiredMsg = rule.ErrorMessage;
             }
         }
     }