Frage

Here it is the question may duplicate but, Want to present my perspective. I have a model, with some annotations. But same model I want to use in different views as strongly typed. But in first view I want to use all annotations, in second view I do not want to use data annotations at all, and in third view I want to use few of fields to be data annotated.

Say FirstName is required in 1'st view. Same field is not required in second view. How custom Validation attribute I need to prepared ? Or do I need to provide validation interface? Please guide me.

War es hilfreich?

Lösung

Extending the awesome answer by Peter Kiss

You will setup a base class without annotations, then create subclasses with unique requirements. Consider the following:

public class UserModel
{
    public int ID { get; set; }
    public virtual string FirstName { get; set; } // Notice the virtual?
    public string LastName { get; set; }
}

// Used for creating a new user.
public class InsertUserModel : UserModel
{
    [Required]
    public override string FirstName { get; set; } // Notice the override?
}

// Used for updating a user.
public class UpdateModel : UserModel
{
    // Custom validation
    [FirstNameUnique("This name is already taken.")]
    public override string FirstName { get; set; }
}

Important

You must decorate your base-properties with virtual modifier, indicating that it can be overridden (or replaced) in the subclasses. Then in the subclasses, properties that will replace your existing properties must be decorated with override modifier.

Custom Validation

using System.ComponentModel.DataAnnotations;
public class FirstNameUniqueAttribute : ValidationAttribute
{
    public FirstNameUniqueAttribute(string errorMessage)
    {
        this.ErrorMessage = errorMessage;
    }

    public override bool IsValid(object value)
    {
        string firstName = value as string;

        // This condition is for properties with validations
        // but not required. Kinda like [StringLength], with
        // validation but not required.                                                           
        if (string.IsNullOrEmpty(firstName))
        {
            return true;
        }

        // Put validation logic here.

        return valid;
    }
}

Andere Tipps

It is called inheritance.

You can create an ultimate base class with no annotations and then you can override each virtual property with the attributes you want to use. The ASP.NET MVC infrastructure view handling isn't working on the object's runtime type instead of it is using the compiled type (@model YourViewModelType).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top