asp.net - 如何使用 ASP.NET MVC 中的正确键向 ModelState 添加错误?

标签 asp.net asp.net-mvc

我想在我的 Controller 中执行一些简单的表单验证。

这是 Controller 操作的摘录:

// other code

            if (!string.IsNullOrEmpty(editModel.NewPassword)
                && editModel.RepeatNewPassword != editModel.NewPassword)                {
                // problem line... How to I get the key from editModel?
                ModelState.AddModelError("", "The new password does not match the repeated password.")
            }

// other code

看来必须使用字符串作为错误的键。有没有办法可以从模型中生成正确的 key ,或者我应该检查输入名称 Html.PasswordFor(x => x.NewPassword)返回?

最佳答案

不完全是你所要求的,但会解决你的问题:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
    #region [ Fields ]

    /// <summary>
    /// Defines the default error messsage
    /// </summary>
    private const string DefaultErrorMessage = "'{0}' and '{1}' do not match.";

    /// <summary>
    /// Defines a typeId
    /// </summary>
    private readonly object typeId = new object(); 

    #endregion

    #region [ Constructors ]

    /// <summary>
    /// Initializes a new instance of the PropertiesMustMatchAttribute class.
    /// </summary>
    /// <param name="originalProperty">The original property name</param>
    /// <param name="confirmProperty">The confirm (or match) property name</param>
    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
        : base(DefaultErrorMessage)
    {
        this.OriginalProperty   = originalProperty;
        this.ConfirmProperty    = confirmProperty;
    } 

    #endregion

    #region [ Properties ]

    /// <summary>
    /// Gets the confirm property name
    /// </summary>
    public string ConfirmProperty { get; private set; }

    /// <summary>
    /// Gets the original property name
    /// </summary>
    public string OriginalProperty { get; private set; }

    /// <summary>
    /// Gets a unique identifier for this <see cref="T:System.Attribute"/>.
    /// </summary>
    /// <returns>An <see cref="T:System.Object"/> that is a unique identifier for the attribute.</returns>
    /// <filterpriority>2</filterpriority>
    public override object TypeId
    {
        get
        {
            return this.typeId;
        }
    }

    #endregion

    #region [ Overrides ]

    /// <summary>
    /// Applies formatting to an error message, based on the data field where the error occurred. 
    /// </summary>
    /// <returns>An instance of the formatted error message.</returns>
    /// <param name="name">The name to include in the formatted message.</param>
    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, this.OriginalProperty, this.ConfirmProperty);
    }

    /// <summary>
    /// Determines whether the specified value of the object is valid. 
    /// </summary>
    /// <returns>true if the specified value is valid; otherwise, false.</returns>
    /// <param name="value">The value of the object to validate. </param>
    public override bool IsValid(object value)
    {
        var properties      = TypeDescriptor.GetProperties(value);
        var originalValue   = properties.Find(this.OriginalProperty, true /* ignoreCase */).GetValue(value);
        var confirmValue    = properties.Find(this.ConfirmProperty, true /* ignoreCase */).GetValue(value);
        return Equals(originalValue, confirmValue);
    } 

    #endregion
}

进而:
[PropertiesMustMatch("NewPassword", "RepeatNewPassword ", ErrorMessage = "The new password and confirmation password do not match.")]
public class YourModel
{
     public string NewPassword {get;set;}
     public string RepeatNewPassword {get;set;}
}

关于asp.net - 如何使用 ASP.NET MVC 中的正确键向 ModelState 添加错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4454269/

相关文章:

javascript - 尝试 Eval() 时解析器错误

c# - 无法成功启动或连接到子 MSBuild.exe 进程。验证 MSBuild.exe

ASP.NET Web Api Controller 子文件夹路由

javascript - 通过 GridView 的客户端 API 访问行数据

asp.net-mvc - ASP.NET MVC 自定义授权

asp.net-mvc - 如何将函数序列化为 json(使用 razor @<text>)

c# - 如何使用 EnumDropDownListFor 获得默认选定的枚举?

c# - 业务逻辑层是否需要自己的模型

c# - 当事件是 ASP.NET 中的第三个部分文件的一部分时,为什么它可能不会注册?

asp.net - 处理大量后置变量 ASP.Net