开发者

How can I add errors to ModelState using the correct key in ASP.NET MVC?

开发者 https://www.devze.com 2023-01-30 14:17 出处:网络
I want to perform some simple form validation in my controller. Here\'s an excerpt from the controller action:

I want to perform some simple form validation in my controller.

Here's an excerpt from the controller action:

// 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

It appears that must use a string as the error's key. Is there a way i can开发者_高级运维 generate the corect key from the model, or should I just check for what input name Html.PasswordFor(x => x.NewPassword) returns?


Or in your ViewModel you can do this

    public class ClassName
    {
        public string Password { get; set; }

        [Compare("Password" , "Password Must Match")]
        public string ConfirmPassword { get; set; }
    }

this is new to mvc3 and you can implement your custom attribute like this fairly easy in mvc3

because IsValid now recives a ValidationContext parameter which contains information about the validation that is being performed like the type of the model and metadata associated with it so you can use reflection to get other properties and their value the CompareAttribute made use of this feature


Not exactly what you are asking for, but will solve your problem:

[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
}

And then:

[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;}
}
0

精彩评论

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