ASP.NET MVC - Attribute that writes to a View

16

I need to write a Attribute that writes a mask validation to View. For example, I would like to mark a property in the Model with a [CEP] , write the following in the View:

<script type='text/javascript'>
    $(document).ready(function () {
        {
            $('#MaskedCEP').mask('99999-999');
        }
    });
</script>
    
asked by anonymous 17.03.2014 / 23:59

1 answer

10

Idea 1:

One way to do this would be to add the [UIHint("Cep")] attribute to your model, and then create a template editor named "Cep.cshtml" that renders exactly what you want.

Idea 2:

Another way to do this would be to create a type Cep (without being an attribute) and then use that type, creating a template editor for it, as well as a custom model-binder for this type. p>

Example using UIHint

Inheritance attribute of UIHint:

public sealed class CepHintAttribute : UIHintAttribute
{
    public CepHintAttribute() : base("Cep") { }
}

Template editor, which should be placed in the views folder in Shared\EditorTemplates , with 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 template 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)
    
18.03.2014 / 00:16