开发者

ASP.Net MVC3 - Custom data annotation to force to upper-case

I'd like to create a custom data annotation that will force the data entered to be upper-cased. If the user types something in lower-case, it should be automatically (and silently) converted to upper-case. This is not a validation issue.

I'd like something like this:

public class Address {
    public string Address {get; set;}
    public string City {get; set;}

    [ForceUpperCase]
    public string State{get; set;}

}

For example, when using @HTML.EditorFor(x => x.State) I'd like the HTML that's created开发者_如何学Go to take care of all of this for me - I don't want to have to write jQuery calls to change the data or force in a particular class name.


I could be wrong, but I don't see a way of doing this with an attribute. But you can always use a backing field for your property, like so:

public class Address {
    private string _state;

    public string Address {get; set;}
    public string City {get; set;}

    public string State
    {
        get { return _state; }
        set { _state = value.ToUpper(); }
    }
}

Sure, it is much uglier, but it works.


My line of code in the view is:

@Html.TextBoxFor(model => model.BldgNameAbbv, new {onkeyup="InputToUpper(this);"})

The associated script is:

<script>
function InputToUpper(obj)
{
    if (obj.value!="")
    {
    obj.value = obj.value.toUpperCase();
    }
}
</script>

This worked for me. And using TextBoxFor, instead of EditorFor, was essential.

For EditorFor:

@Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control", @onkeyup = "InputToUpper(this);" } })


You can also force upper case in CSS with text-transform property. (See this)

CSS:

.upperCase 
{
    text-transform: uppercase !important;
}

!important is not mandatory.


View (Razor):

@Html.EditorFor(model => model.Property, new { htmlAttributes = new { @class = "upperCase" } })

if you use traditional html, you just need to add the html attribute class="upperCase" on your input.

Html:

<input type="text" class="upperCase"/>

See example here: https://jsfiddle.net/ahLw7uq2/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜