首页 > 解决方案 > 通过从C#中的类调用函数来显示消息

问题描述

[Stringlength(ErrorMessage= "Get value")] 我想如何将此行用作通用行。即我希望它接收我在课堂上的消息文本。

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength:19, ErrorMessage = Helpers.Helpers.DisplayMessage(maxLength: 19, message: "display message") )]
    public long UserId { get; set; }

例如:helpers.cs 当我调用 DisplayMEssage 函数时,我希望它返回我设置的值,但我不能。我怎样才能做到这一点?

public class Helpers
{
    public static string DisplayMessage(string maxLength )
    {
        set
        {
            return "test";
        }
        get
        {
            return "Sonucccc";
        }
    }
}

模型

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength:50, ErrorMessage = Helpers.Helpers.MessageDisplay(message: "Up to {50} characters can be entered.") )]
    public long Username { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength:50, ErrorMessage = Helpers.Helpers.MessageDisplay(message: "Up to {50} characters can be entered.") )]
    public string Email { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength:25, ErrorMessage = Helpers.Helpers.MessageDisplay(message: "Up to {25} characters can be entered.") )]
    public string Business { get; set; }

标签: c#.netvisual-studio.net-core

解决方案


也许这可以帮助

您可以创建自定义属性并设置ErrorMessage您喜欢的方式

public class CustomStringLengthAttribute : StringLengthAttribute
{
    public CustomStringLengthAttribute(int maximumLength): base(maximumLength)
    {
        this.ErrorMessage = "your error";
    }
}

cunstructor 中也可以有参数:

public class CustomStringLengthAttribute : StringLengthAttribute
{
    public CustomStringLengthAttribute(int maximumLength, string msg): base(maximumLength)
    {
        this.ErrorMessage = msg;
    }
}

并像这样使用它:

[CustomStringLengthAttribute(50, "Up to {50} characters can be entered.")]     
public string Email { get; set; }

推荐阅读