Asif Hameed
Asif Hameed

Reputation: 1423

making model property optional

I am working on asp.net MVC 3 application and I have created a model. I am using Entity Framework 4.1 Code First approach. I have a property like this:

 [Required]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

I am using it in two views. I want to make it required in one view but in other view I want to make it optional.

Any suggestions for this please ?

Upvotes: 0

Views: 2548

Answers (1)

Per Kastman
Per Kastman

Reputation: 4504

Don't expose the class directly to the view, use a view model for each page and have different attributes there. Then map to the ef type in your controller.

public class Page1ViewModel
{
    [Required]
    [Display(Name = "Email Address")]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage= "Invalid Email Address")]
    public string Email { get; set; }

    //Other properties

}

public class Page2ViewModel
{
    [Display(Name = "Email Address")]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage    = "Invalid Email Address")]
    public string Email { get; set; }

    //Other properties
}

Upvotes: 1

Related Questions