Alex Rivera | Logout

Is it correct way to use ModelState.Remove to deal with ModelState?

Asked 2011-07-27T10:55:30.220
25

Im working on a big MVC3 web application and have an annoyance regarding the ModelState.IsValid method.

ModelState is being used in nearly all of my controllers so to validate the data being posted. The views are all based on ViewModels which contain different classes and these classes obviously contain properties which could be marked as [Required].

The problem i am having is the required properties are sometimes not required and im having to use the ModelState.Remove method so that ModelState.IsValid becomes true.

My question is by using ModelState.Remove, is this the correct way of doing things or is there a more efficient approach.

Edit
Report

1 Answer

1

I'm totally with Mr.Steve Morgan

So if your ViewModel doesn't always need some property to be Required then you shouldn't decorate it as Required.

I don't know why you wanna this issue but I suppose that in some cases you need PropertyOne to be Required if PropertyTwo has value. In this case you may need to make your CustomValidationAttribute to check these two properties.

I'm using something like this :

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class PropertyNeededAttribute : ValidationAttribute
{
    private const string defaultErrorMessage = "'{0}' needs '{1}' to be valid.";

    public PropertyNeededAttribute(string originalProperty, string neededProperty)
        : base(defaultErrorMessage)
    {
        NeededProperty = neededProperty;
        OriginalProperty = originalProperty;
    }

    public string NeededProperty { get; private set; }
    public string OriginalProperty { get; private set; }

    public override object TypeId
    {
        get { return new object(); }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                             OriginalProperty, NeededProperty);
    }

    public override bool IsValid(object value)
    {
        object neededValue = Statics.GetPropertyValue(value, NeededProperty);
        object originalValue = Statics.GetPropertyValue(value, OriginalProperty);
        if (originalValue != null && neededValue == null)
            return false;
        return true;
    }
}

note: Statics.GetPropertyValue(...) do nothing but get the value from the property to compare it.

Hope this helped :)

answered 2011-07-27T12:59:36.670

Your Answer