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
cshtml. Add the "[Required]" attribute to the field that you want to make mandatory for insertion. The required attribute requires the "System. ComponentModel.
To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.
We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.
ComponentModel. DataAnnotations namespace that you can use to apply to (decorate) classes or properties to enforce pre-defined validation rules.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With