tags:

views:

48

answers:

2

Seeing as though ASP.NET MVC 2 Preview 1 was just released it means the way things are done may be slightly different in terms of the model. The DataAnnotation feature allowing validation to be done against properties in its model is good, but I'm not sure where to put it.

I create my models manually as recommended in Steve Sanderson's book on ASP.NET MVC, which suits me perfectly. Should I have a separate model, however, for POST data coming from a view page? So say I were creating product items, my main model may look like this:

public class Product {
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] public int ProductID { get; set; }
    [Column] public string ProductName { get; set; }
    [Column] public string ProductDescription { get; set; }
    [Column] public double ProductCost { get; set; }
}

Now Scott's example gives us DataAnnotations so you can do:

public class Product {
    public int? ProductID { get; set; }

    [Required(ErrorMessage="Must enter a product name!")]
    public string ProductName { get; set; }

    public string ProductDescription { get; set; }

    [Range(1, 500, ErrorMessage="Too expensive!")]
    public double ProductCost { get; set; }
}

The latter example would have a nullable ProductID field because it would be an auto-increment field in the database. Now both of these examples would be contained in classes, and probably with the same name. Personally I don't think my main model should have these annotations in them as it shouldn't be their responsibility to validate data. So should I have separate namespaces with classes in them having different roles?

+1  A: 

In my opinion validation is part of your model's concerns - keep them together.

UpTheCreek
+1  A: 

Personally I have a single model that is sent to the view and posted to the controller and usually name them something like ProductEditModel. This is then validated and converted to my Product type in the controller.

This View Model is usually wrapped in some type of presentation model for all the data on the view that isnt going to change over the lifecycle of the page eg. Menu items, user name etc.

Check this sreencast out http://serialseb.blogspot.com/2009/05/my-mvc-best-practices-talk.html it will explain it better and is a really good approach to mvc dev

Colin G