1
pimps
106 days, 22 hours, 51 minutes ago
Sunday, October 25, 2009 9:18:16 PM GMT Sunday, October 25, 2009 1:56:01 PM GMT

ASP.NET MVC View Model Patterns

ASP.NET MVC View Model Patterns
 
geekswithblogs.net -- Since MVC has been released I have observed much confusion about how best to construct view models. Sometimes this confusion is not without good reason since there does not seem to be a ton of information out there on best practice recommendations.  Additionally, there is not a “one size fits all” solution that acts as the silver bullet. In this post, I’ll describe a few of the main patterns that have emerged and the pros/cons of each. It is important to note that many of these patterns have emerged from people solving real-world issues. Another key point to recognize is that the question of how best to construct view models is *not* unique to the MVC framework.  The fact is that even in traditional ASP.NET web forms you have the same issues.  The difference is that historically developers haven’t always dealt with it directly in web forms – instead what often happens is that the code-behind files end up as monolithic dumping grounds for code that has no separation of concerns whatsoever and is wiring up view models, performing presentation logic, performing business logic, data access code, and who knows what else.  MVC at least facilitates the developer taking a closer look at how to more elegantly implement Separation of Concerns. Pattern 1 – Domain model object used directly as the view model Consider a domain model that looks like this: 1: public class Motorcycle 2: { 3: public string Make { get; set; } 4: public string Model { get; set; } 5: public int Year { get; set; } 6: public string VIN { get; set; } 7: } When we pass this into the view, it of course allows us to write simple HTML helpers in the style of our choosing: 1: =Html.TextBox("Make") %> 2: =Html.TextBoxFor(m => m.Make) %> And of course with default model binding we are able to pass that back to the controller when the form is posted: 1: public ActionResult Save(Motorcycle motorcycle) While this first pattern is simple and clean and elegant, it
beebee posted 107 days, 6 hours, 13 minutes ago     show counter code
tags: C# 3.0, mvc

No comments yet, be the first one to post comment.

To post your comment please login or signup