Monday, August 30, 2010

Organizing View Models with Namespaces

In Asp.Net MVC, each view should, preferably, have a strongly typed view model.  For a given controller, it could serve up multiple views through actions or simply by rendering partial views.  Sometimes using same view model name for different views make sense while the view model implementations are quite different.  For instance, I might have a view model named ProductForm for a view named Index as follows

public class ProductModel
{
  [DisplayName("Product Id")]
  public Guid Id { get; set; }
  public string Name { get; set; }
  public string Category { get; set; }
}

and I also have a view model for a view named Edit:

public class ProductModel
{
  [DisplayName("Product Id")]
  public Guid Id { get; set; }
  [Requried]
  public string Name { get; set; }
  [Requried]
  public Category Category { get; set; }
}

public enum Category
{
   Hardware,
   Software,
}
The difference between the two models are obvious.  In this case, to distinguish the two models, I could use different names for each or separate them using name space.  I find it easier to use namespace the models and it also follows the pattern convention which Mvc uses to locate a view for a controller as follows:


Models
  |---Home (controller name)
       |--- Index (view name)
            |--- ProductModel.cs (view model)








       |--- Edit (view name)
            |--- ProductModel.cs (view model)


So the name space looks like as follows:
UI.Home.Index.ProductModel
UI.Home.Edit.ProductModel

No comments:

Post a Comment

About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers