Reputation: 473
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 ([email protected])!!!")]
[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
Upvotes: 5
Views: 2664
Reputation: 156
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;
}
}
}
Upvotes: 7
Reputation: 11544
Modify your template to this:
@model string
@Html.TextBoxFor(m => m)
@Html.ValidationMessageFor(model => model, "", new { @class = "text-danger" })
Upvotes: 3