C# How to use DataAnnotations StringLength and SubString to remove text

前端 未结 3 760
無奈伤痛
無奈伤痛 2021-02-19 09:10

I have a model classes that has a description property with a data annotation attribute of StringLength and length is set to 100 characters. When this property is more than 100

相关标签:
3条回答
  • 2021-02-19 09:35

    Create a view model that doesn't have a data annotation for the length, then you can map it to the entity model and truncate the value if it's longer than 100.

    0 讨论(0)
  • 2021-02-19 09:39

    You could always check the attribute value using reflection, though that approach is not the best if you can get around it - it's not pretty:

    var attribute = typeof(ModelClass).GetProperties()
                                      .Where(p => p.Name == "Description")
                                      .Single()
                                      .GetCustomAttributes(typeof(StringLengthAttribute), true) 
                                      .Single() as StringLengthAttribute;
    
    Console.WriteLine("Maximum Length: {0}", attribute.MaximumLength);    
    
    0 讨论(0)
  • 2021-02-19 09:54

    Why all the hassle? Why not

    private string _description = string.Empty;
    
    [StringLength(100, ErrorMessage = "Description Max Length is 100")]
    public string Description 
    {  
        get { return _description; }
        set { _description = value.Substring(0,100); };  // or something equivalent
    } 
    
    0 讨论(0)
提交回复
热议问题