Turo
Turo

Reputation: 1607

Prevent to use default model data annotations in ViewModel

I started working on my first serious MVC project for school unfortunately without defining the data annotations to the model first (so did not set "required" annotation, limit to size of attribute names etc.). I work with a viewmodel, and after adding the annotations the model is causing my ViewModel state to get invalid when posting the form.

It seems like it's the email required that is causing the issue. It is not used on viewmodel and in the form and it seems the viewmodel expects it will get it. Is there a way the form to stop demanding this field by setting some limitation in viewmodel (or controller). I would really prefer not to change the structure of the application (if I start from the scratch I would probably do this a bit different, but not much time is left to finalize the project)

Customer (Model)

public Class Customer(){
    public int Id { get; set; }

    [Required(ErrorMessage = "Required")]
    [StringLength(25, ErrorMessage = "Message"]
    public string Name { get; set; }

    public string Logo { get; set; }

    //[Required(ErrorMessage = "Email required")]
    //[Display(Name = "E-mail")]
    //[RegularExpression(xxxx, ErrorMessage = "not correct")]
    public string Email { get; set; }

    public int UserId { get; set; }
}

ViewModel

public class CustomerEditViewModel
        {
        public Customer Customer { get; set; }

        [FileTypes("jpg,jpeg,png")]
        [FileSize(1024 * 1024, ErrorMessage = "Max x bytes")]
        public HttpPostedFileBase File { get; set; }
        }

Upvotes: 0

Views: 113

Answers (1)

NikolaiDante
NikolaiDante

Reputation: 18639

You can remove errors from the modelstate in your controller, e.g.

   this.ModelState[key].Errors.Clear();

where key is the bit to be cleared, so if it's email it's most likely -

   this.ModelState["Customer.Email"].Errors.Clear();

Upvotes: 1

Related Questions