0

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; }
        }
Turo
  • 1,537
  • 2
  • 21
  • 42
  • Are you sure its the email? The code you posted doesn't seem that way. My guess is it is most likely one of the two Ids. if they are not nullable ints then MVC makes them required anyways. – Brad C Jun 28 '15 at 18:42
  • 1
    You need to show your POST method to understand what your trying to do. If your form does not contain a control for `Customer.Email` then your view model is not correct (see [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc)) –  Jun 28 '15 at 23:32
  • Thank you Stephen. Yeap, I realize I should better not use complex entity like Customer in the ViewModel. I just went around this time and added the email editing possibility to the view and it works fine - it was actually a functionality I had not thought of :) Next time I would go about it differently anyways. – Turo Jun 29 '15 at 00:13

1 Answers1

1

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();
NikolaiDante
  • 18,469
  • 14
  • 77
  • 117
  • sorry I was too fast. ModelState is valid then, but the TryUpdateModel(vm) is not working.. – Turo Jun 28 '15 at 19:20