【问题标题】:ASP.Net MVC3 - Custom data annotation to force to upper-caseASP.Net MVC3 - 自定义数据注释强制为大写
【发布时间】:2011-07-01 21:12:46
【问题描述】:

我想创建一个自定义数据注释,强制输入的数据为大写。如果用户以小写形式键入内容,则应自动(并且静默地)将其转换为大写。这不是验证问题。

我想要这样的东西:

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

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

}

例如,在使用 @HTML.EditorFor(x => x.State) 时,我希望创建的 HTML 可以为我处理所有这些 - 我不想编写 jQuery 调用更改特定类名中的数据或强制。

【问题讨论】:

    标签: asp.net-mvc data-annotations uppercase


    【解决方案1】:

    我可能是错的,但我没有看到使用属性执行此操作的方法。但是您始终可以为您的属性使用支持字段,如下所示:

    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(); }
        }
    }
    

    当然,它更丑,但它有效。

    【讨论】:

    • 是的,它有点难看,但它也错过了在浏览器中进行大写转换的愿望,而不仅仅是在回发期间。不过谢谢...
    • 对不起,我误解了你的问题,没有看到你想要客户端的东西。
    【解决方案2】:

    我在视图中的代码行是:

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

    相关的脚本是:

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

    这对我有用。并且使用 TextBoxFor,而不是 EditorFor,是必不可少的。

    对于编辑器对于:

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

    【讨论】:

      【解决方案3】:

      您还可以使用 text-transform 属性在 CSS 中强制大写。 (See this)

      CSS:

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

      !important 不是强制性的。


      查看(剃刀):

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

      如果您使用传统的 html,您只需在输入中添加 html 属性 class="upperCase"。

      HTML:

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

      在此处查看示例:https://jsfiddle.net/ahLw7uq2/

      【讨论】:

      • 在后端它仍然是原来的情况
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多