profile for Cullen Tsering at Stack Overflow, Q&A for professional and enthusiast programmers

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

0 comments:

Post a Comment

About Cullen

Cullen has been coding since 1991. He has been a Sr. Software Engineer/Architect for 11 years and counting. He enjoys coding for work as well as for fun. He loves learning from anyone and delights in sharing the little knowledge he possesses.

Followers