Idea 1:
One way to do it would be to add the attribute [UIHint("Cep")]
in your model, and then create an editor-template with the name "Cep.cshtml" that renders exactly what you want.
Idea 2:
Another way to do that would be to create a type Cep
(without being an attribute) and then use this type, creating a template-editor for it, as well as a custom model-Binder for this type.
Example using UIHint
Attribute inheriting from Uihint:
public sealed class CepHintAttribute : UIHintAttribute
{
public CepHintAttribute() : base("Cep") { }
}
Editor template, which should be placed in the views folder in Shared\EditorTemplates
, by the name of Cep.cshtml
:
@model object
@{
var fieldId = this.ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
var fieldName = this.ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
}
<script type='text/javascript'>
$(document).ready(function () {
{
$('#@fieldId').mask('99999-999');
}
});
</script>
<input type="text" name="@fieldName" id="@fieldId" value="@this.Model"/>
View model class:
public class Endereco
{
public int Id { get; set; }
public string Complemento { get; set; }
public string Logradouro { get; set; }
public string Numero { get; set; }
[CepHint]
public string Cep { get; set; }
}
And finally in the view where you want to show the field, use EditorFor
:
@model ClienteData
@* ... um pouco mais abaixo no arquivo ... *@
@this.Html.LabelFor(m => m.Cep)
@this.Html.EditorFor(m => m.Cep)
@this.Html.ValidationMessageFor(m => m.Cep)
Poor view... :)
– bfavaretto
I thought that, but it looks like a cannonball to me for a problem that should be more simple: Input Masking in MVC 4 using Data Annotation
– Miguel Angelo
If that’s what it is, I add in response.
– Miguel Angelo
That’s right, but I once tried to use that solution and it didn’t work at all.
– Leonel Sanches da Silva
I don’t know if it helps, but I use meiomask just put the type of mask in the input alt and make a simple call to all inputs
$('input[type="text"]').setMask();
– Leandro Amorim
@Leandroamorim I don’t want any specific code in the View because the Views are generated by Scaffold, and this would give me some rework.
– Leonel Sanches da Silva