How we do MVC – View models

A while back, I went over a few of the patterns and opinions we’ve gravitated towards on our current large-ish ASP.NET MVC project, or, how we do MVC.  Many of these opinions were forged the hard way, by doing the wrong thing many times until we found the “right” opinion.  Of course, many of these opinions are only really valid in the constraints of our project.  While the domain of this project isn’t important, here are some key aspects to consider:

  • AJAX is used very, very sparingly.  Section 508 compliance is required
  • XHTML compliance is also required
  • XHTML DTD validation is also required
  • All (well, 99%) operations revolve a single uber-entity.  Think customer relationship management, where everything you do deals with exactly one customer
  • Snippets of information repeated across many screens
  • Screens are either edit, or view, but never both.  (99% never)

Given these constraints, these opinions may or may not apply to the project you work on.  Again, patterns are all about tradeoffs, benefits and liabilities.  But, opinionated software is like building a bullet train.  It goes extremely fast, but only in the direction you build it.

That said, I’m going to go over some of the main aspects of our MVC usage in a series of posts – starting with ViewModels.

ViewModel design

For our application, the ViewModel is a central aspect of our MVC architecture.  One of the first dilemmas facing MVC developers is to decide what the “M” in MVC means in ASP.NET MVC.  In Rails, this is fairly clear, the M is ActiveRecord (by default).  But in ASP.NET MVC, the “M” is silent!  Its out-of-the-box architecture offers no guidelines nor advice on what the M should be.  Should it be an entity?  Data access object?  DTO?  Something else?

Sidenote – the term DTO is far overused.  DTO is a Data Transfer Object.  The pattern describes the usage, not the shape of a type.  Just because an object is all properties and no methods does NOT mean it’s a DTO.

For us, the ViewModel is inextricably linked to Views, which leads us to our first rule:

Rule #1 – All Views are strongly-typed

I think I’ve gone over this one enough, as I really can’t stand magic strings and loose contracts.  A dictionary as ViewModel is a very loose contract between the Controller and View.  While on rare occasions we still need to pass information in the dictionary part, we’ve limited this to supporting information to help render some of the lower-level pieces of the View, and are used for some “plumbing” pieces, these pieces do not show up in our Controller action nor are they visible when you design the view.

Rule #2 – For each ViewModel type, there is defined exactly one strongly typed View

We’ll get into how we do this soon, but this rule has a lot of implications:

  • ViewModel types are distinct from our Domain Model types
  • The choice of what View to show can be decided strictly on the shape of your ViewModel
  • Re-used pieces in a View (through Partials) can be decided through re-using ViewModel types

image

On the first point, we never pass an Domain Model entity straight into the view.  Most of the time, we only show a slice of information from a single entity.  And many other times, the same snippet is shown in many places.

Rule #3 – The View dictates the design of the ViewModel.  Only what is required to render a View is passed in with the ViewModel.

If a Customer object has fifty properties, but one component only shows their name, then we create a custom ViewModel type with only those two properties.  Because we only have one ViewModel type per View, we shape our ViewModel around only what is displayed (or used) in that View.  Why is this a Good Thing?

For one, just having a ViewModel points us to the right View.  We need any other information other than your ViewModel type to pick the correct View.  This also means we no longer need to concern ourselves with locating views by some arbitrary name, as the ViewModel is the View.  Things like RenderPartial, which I have to select a name, become rather pointless at that point.

Rule #4 – The ViewModel contains only data and behavior related to the View

For the most part, our ViewModel contains only data.  Most, if not all aggregations/calculations or shaping is done through our Domain Model.  But occasionally, we have View-specific behavior or information, and that rightly belongs on our ViewModel.

We’ve looked at how we design our ViewModel and what it looks like, but how does it get there?  If we create all these distinct ViewModel types separate from our Domain Model, didn’t we just create a bunch of work for ourselves?  We thought so too, which is why we developed AutoMapper on this project.

Building the ViewModel

When we introduced AutoMapper into our MVC pipeline, we had a real problem.  Do Controllers need to do the mapping between Domain Model and ViewModel in each action method?  That becomes rather annoying for unit testing, as the mapping operation could warp things to a state that it becomes difficult to pull things back out.  For example, or EditModels (ViewModels for forms) are very string-y, where DateTimes, Ints, Decimals etc are represented as strings.  This comes from us using Castle Validators (future post, I promise) for validation. 

So more moving parts, a dependency across all controllers?  No, mapping in our Controller action just won’t do.  Instead, we’ll use an Action Filter to do the work for us:

image

A request comes in, handled by an Action.  The Action does its thing, ultimately deciding how to respond to the request.  In many cases, this means rendering a view (ViewResult).  From there, our Action Filter comes into play.  On our Action method, we decorate it with an AutoMap attribute to configure the source/destination type pair to be mapped:

[AutoMap(typeof(Product), typeof(ShowProduct))]
public ActionResult Details(int id)
{
    var product = _productRepository.GetById(id);

    return View(product);
}

Very trivial, yes, but here we see that we still use the strongly-typed version of the View method, so that means that our model on the Action side, which I call the Presentation Model (feel free to pick a better name), is the strongly-typed ViewModel for the moment.  The Presentation Model, which the Action creates, can be an entity, an aggregate root, or some other custom aggregate component that we build up.

From there, we decorated our action with a filter that specified we need to map from Product to ShowProduct.  Why do we have to specify the source type?  Well, many ORMs, including NHibernate, rely on proxy types for things like lazy loading.  Instead of relying on the runtime type, we’ll explicitly specify our source type directly.  This also helps us later in testing, as we can whip through all of our controller actions using reflection, and test to make sure the source/destination type specified is actually configured.

The filter attribute is very simple:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class AutoMapAttribute : ActionFilterAttribute
{
    private readonly Type _sourceType;
    private readonly Type _destType;

    public AutoMapAttribute(Type sourceType, Type destType)
    {
        _sourceType = sourceType;
        _destType = destType;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var filter = new AutoMapFilter(SourceType, DestType);

        filter.OnActionExecuted(filterContext);
    }

    public Type SourceType
    {
        get { return _sourceType; }
    }

    public Type DestType
    {
        get { return _destType; }
    }
}

We simply capture the types and delegate to the real action filter for the work.  This is again because I believe in separating metadata in attributes from the behavior they perform.  Attributes just don’t work well for behavior.  Instead, I’ll create a separate action filter:

public class AutoMapFilter : BaseActionFilter
{
    private readonly Type _sourceType;
    private readonly Type _destType;

    public AutoMapFilter(Type sourceType, Type destType)
    {
        _sourceType = sourceType;
        _destType = destType;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var model = filterContext.Controller.ViewData.Model;

        object viewModel = Mapper.Map(model, _sourceType, _destType);

        filterContext.Controller.ViewData.Model = viewModel;
    }
}

The BaseActionFilter is just a class that implements the various filter methods as virtual members, so I can override just the ones I need to use.  The AutoMapFilter pulls the original PresentationModel out of ViewData, performs the mapping operation, and puts the mapped ViewModel into the ViewData.Model property.  From there, the strongly-typed view for our specified ViewModel type is rendered.

Because AutoMapper can flatten source types, we often find our ViewModel to simply follow a property chain for various pieces of information.  Again, we let our View shape that piece.  If we decide not to flatten, it’s usually because we’re creating a partial that re-uses a ViewModel type across other parent ViewModel types.

Wrapping it up

Designing ViewModels is quite ambiguous with MVC, as the shipped platform doesn’t offer any guidance or opinions in that area.  But by forming rules around our ViewModel, we can create a path and direction for our innovation.  Our rules are designed to strengthen the relationship between the View and the Model, with a concept of ViewModel – a Model designed exclusively for exactly one View.

In the next post, we’ll look at designing our views – for both viewing and editing data, and how we’ve crafted opinionated HTML builders to eliminate a lot of duplication and enforce standardization.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in ASP.NET MVC, AutoMapper. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Jake Scott

    It would be really cool if you have a demo project somewhere that we can download, is this in the pipeline? So next up is learning how you post data.

    It would be cool to know how you do binding of these view models, validation as well as your approach for mapping these back into models…

    Cheers
    Jake

  • http://blog.mickdelaney.com mick delaney

    do u see all these ideas merging into an opinionated framework on top of mvc?
    i’ve been doing some rails dev too and 1 of the strengths is that some of the decisions have been made, i see u are involved in tarantino, but we also have sharparc, mvccontrib etc… will we see something like Fubu mvc on top of asp.net mvc?

  • le tot

    We are doing almost the same, using a view model, our problem is that we have a anemic ddd, we don’t know all the domain, and probably never do (yes, sad but true), to fill the view model we use a separate class for each view, a task class, that returns the strongly type ViewModel from our domain, , and each task class uses a Map class that do the map (we are doing this to be able to test the maps), we don’t use an attribute based map, but now we will see if that approach can fit.
    Regards.-

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Jake

    Yeah, all of those topics are in the pipeline. As far as a demo project, CodeCampServer is about as close as it gets out there right now. It was built with many concepts of our current project, but a lot of different ones too.

    @Mick

    I doubt it. Many of our choices were dictated by the constraints of our project, while others we want to apply broadly.

    Design of our controllers/actions is probably not going to be lifted to other places, and it’s also why I generally won’t talk about controller design. Honestly, a lot of the stuff we did isn’t built to be consumed outside of this project. The concepts, however, are fairly straightforward to re-do.

  • Mark Keller

    We are also doing pretty much the same thing. The only real difference is that we don’t quite do the 1:1 view – viewmodel mapping. we’ll reuse viewmodels for detail views vs. edit/create views. I like the use of the automapper attribute

    The question we are still trying to hash out is where the heck to put the User info such as username, roles, is logged in, etc…? Are you sticking this in some kind of base viewmodel? separate json calls? it doesn’t feel right to put it into the requested action’s viewmodel, but not really sure where else to put it. I’d love to hear how you are handling that kind of info needed for your views.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Mark

    RenderAction is your friend here. It’s perfect for orthogonal concerns for a request. I think of it like chain of responsibility/decorator – a bunch of disparate actions get a crack at a request, pulled together by a master view page directing where the resultant HTML goes.

  • http://heliosfx.com Travis

    How are you handling data that is needed in a ViewMasterPage? I have my own ideas, but I would like to hear yours.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Travis

    I really don’t like action filters used to supply ViewData – I go for the RenderAction route instead. I’d also rather not set up some inheritance hierarchy for my ViewModel for information in a master page either.

    I know that master pages can be strongly typed, but I don’t really know how that would work.

  • http://heliosfx.com Travis

    @bogardj well the inheritance hierarchy is the route I went, and it just does not feel right. It would be interesting if others would chime in.

  • http://www.lostechies.com/members/jcteague/default.aspx jcteague

    The fact that you are typically dealing with one entity per action gives you the ability to leverage AutoMapper. We tried using AM on our latest proejct, but did not get a lot of mileage from it because almost all of the data we were sending to view came from multiple sources. It would be cool if I could use multiple sources for AM. Is that possible?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @John

    So we have two choices – one is to create an intermediate presentation model to hold everything. It makes a lot of sense where you have a composite presentation model with behavior or composes information.

    Otherwise, I’m looking at a feature for the next AM version to provide the ability to “Fill” a destination object. It’s something we’ve wanted here and there, but always solved by creating an intermediate model on the controller side.

  • http://meandmycode.com Stephen

    Looks similar to what we do, only we didn’t use automapping and thus not the implicit mapping of model to viewmodel..

    Personally I wonder how that even works, we’ve found for even simple perf requirements where relational data exists, that a controller action must know far to much than seems ‘right’ about the view in order that it only retreives the relevant information and selects almost straight into a view model.. we thus only tend to use the ‘model’ as a concept for the query..

    for example:

    from p in Products
    where …
    select new ProductDetailsView(p.Name, …);

    Things end up messy, but it seems its either messy or has scary performance issues.. selecting an entire model out to give to a view in a blasé ‘you pick what you want from this’ is hugely unrelealistic.

    Not to mention a view might consist of data from multiple ‘unlinked’ models.. such as.. related products.. which would mean we have:

    Product
    RelatedProducts

    We would need to create a model then that encompasses these two, just so that it can then have certain parts ‘picked out’ by the mapper, as it maps to the viewmodel..

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Stephen

    You’d need to couple this with fetching strategies to prevent the problems you’re talking about. But, you’d do this anyway, if it’s a “pick and choose” kind of thing. That’s the other way to go – do the flattening/shaping at the query layer.

    As for things like “related products”, those are some things that I would render using something like RenderAction – as these pieces likely don’t change as much, or change via external events.

    Either way, I’m still not using a dictionary. Why use a dictionary when you can create an object with properties?

  • Ryan

    What do you use for modeling when receiving information back from the user (e.g. the the information posted back to a controller action from an edit form?)

    Do you take in a Domain Object directly, a ‘dumb’ InputModel equivalent of the ViewModel and map it back to your domain object, or something else entirely?

    I have a much harder time figuring out what to use for input models than output.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Ryan

    The same thing that got pushed out. Our EditModel is automapped from the presentation model (domain model or otherwise), and is what’s posted back. We then translate EditModels into one or more commands (it’s not a task-based UI), and execute the business rules and handler for each command. I’ll touch on that stuff soon too.

    Quick note – our edit pages _only_ have input elements, and we generally don’t have view and edit information on one screen.

  • http://lazycoder.com Scott Koon

    Given you initial constraints, how many of your views do you think could be code-gen’ed/written as static HTML rather than a dynamic page?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Scott

    We actually looked at that…but there were some other constraints on our forms that led us away from that. Our forms (for a records management app) have dozens of fields, and our designers wanted to be flexible for overall layout. For us, it was easier to do that in HTML.

  • http://www.lostechies.com/members/jcteague/default.aspx jcteague

    @Jimmy
    What do I gain by AutoMapping an Intermediate model to a ViewModel, when the only purpose of the intermediary is to go to the view?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @John

    Well, sometimes the intermediate model has a real domain concern. Other times, it doesn’t. On the latter, I’m looking at extending AutoMapper to fill and compose a larger object.

    Otherwise, you just get the flattening benefit – where your view matches 1:1 to a view model.

  • http://framework-it.net Brig Lamoreaux

    Hi Jimmy,
    I like to see how others have been using and thinking about MVC. One thing that we do a little different is not having a 1:1 ViewModel to View relationship.
    What I’ve found is there are many cases where two view share 80 percent of the data. This is especially the case when a workflow leads the user from one view to another. In these cases the views in the workflow share the same ViewModel.
    One benefit of doing this is the ViewModel knows how to read and transform Form data into the ViewModel and validate it. Although you mentioned something about EditModels which I would like to know more about.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Brig

    Yeah, we definitely don’t have any workflows. Our forms are one and done. But we’ve stayed completely away from any kind of interaction with the Forms business, that seems a little messy.

  • http://typesafe.be/ Gino

    @ Travis: I did go for ViewModel inheritence as well. However, I don’t feel bad about it… You seem to do, could you share why?

    I think there’s nothing wrong with putting common information (something ALL views that depend on a certain mast page need) in a base class. (http://typesafe.be/index.php/2009/07/04/the-viewmodel-and-the-masterpage/)

  • Nima

    Thank you
    What about paging? I wondering why no sample explaining paging and mapping together. As I remember MVC contrib GridView use IPagedList datasource for paging. It need to map model after data paged by grid.

  • Hans

    It seems to need add the “Mapper.CreateMap” in OnActionExecuted:
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
    var model = filterContext.Controller.ViewData.Model;

    Mapper.CreateMap(_sourceType, _destType);

    object viewModel = Mapper.Map(model, _sourceType, _destType);

    filterContext.Controller.ViewData.Model = viewModel;
    }

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Hans

    Since the CreateMap calls only need to happen once per AppDomain, we do CreateMap calls in Application_Start in global.asax. Inside the Application_Start, we call into a bootstrapper class that configures our IoC container, ORM, AutoMapper, and other static configuration.

  • http://sm-art.biz ulu

    Do you have separate models for Create and Edit views? For List and Details? That must be a lot of duplication. You mention that you reuse view pieces by using partials, how do you reuse model pieces? Is there a sample of this in the CodeCamp?

    ulu

  • http://sm-art.biz ulu

    Do you use separate models for Create and Edit views? For List and Details? Seems to be a lot of duplication here..

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @ulu

    Yes, separate models for View and Edit. But Edit has its own requirements, even the types might be different. Throw in validation, it starts to diverge quite a bit. Not for every application of course, but ours tend to be quite different.

    Typically, our View pages show a lot more associations, where the Edit does not.

  • http://sm-art.biz ulu

    I was actually asking whether you have your Create models different from the Edit models. Or do you reuse the view for Edit and Create?

    Another question is, is your Details model different from the List model? Inherits from it?

    Whenever you add or rename or remove some property from your domain class, how do you keep all these models in synch?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @ulu

    We’ll have a single ViewModel per View, so 1:1 relationship there. In this project, when an edit screen and create screen are exactly the same, we’ll use a single ViewModel type.

  • Omu

    how about the problem of selectlist in asp.net mvc, that you need to provid it with the full list of values and the selected values and you get back in the POST only an int (the selected value)

  • @Omu

    let’s say we have something like this

    public class Person
    {
    public string Name {get; set;}
    public Country Country {get; set;}
    }

    public class PersonViewModel
    {
    public Person Person {get; set;}
    public SelectList Countries {get; set;}
    }

    can automapper be used to perform to parse from Person into PersonViewModel and back ?

  • @@OMU

    I have the same question, or what’s the best practice to put this logic? In automapper, but how about repository access? Or in the controller? Or in a service layer?

  • EvanG

    I am struggling myself with these issues. It seems that the recommendation here is that the Controller should do the mapping. This means you are working with Domain Objects on your Controller. The problem that I see is that if you want to decouple your presentation layer from the Domain Model using DTOs, you need to handler on more mapping. So the number of mappings go as follows: Model–>DTO–>View Model and vice versa….This is just too many mappings…don’t you think? thanks.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Omu

    We have a few different ways of dealing with this, it all depends on if the select lists’ values depend on request values or not. Sometimes it’s built up in the controller, sometimes just indicated in the view.

    @EvanG

    We actually use an action filter to do the mapping. That way, our tests only deal with the domain objects.

    For the most part, it’s domain model -> (autoMapper) -> view model. Other times, we have to create a composite presentation model. So it’s domain model -> presentation model (not mapped, but built) -> view model. Hope this helps!

  • http://geekswithblogs.net/wesm Wes

    Hey Jimmy, I have taken the AutoMapFilter to a bit of an extreme using some AOP ideas, I hope this helps with what you guys are doing, I find it a lot easier to have things just work instead of needing attributes, more of the spirit of FubuMVC.

    Enjoy:

    http://geekswithblogs.net/wesm/archive/2010/01/03/automapfilter-meet-ijoinedfilter.aspx

  • http://twiter.com/adamjford adamjford

    Hey, I’m using the AutoMapAttribute on my controller actions to map objects to my viewmodels, and I’m trying to write unit tests to verify that the correct type is being return by the action. Problem is, it doesn’t appear to be executing the action filter when I call the action in a unit test. Here’s some sample code and a failing test.

    public class ReportsController
    {
    [AutoMap(typeof(AuditReportQueryResults), typeof(AuditReportViewModel))]
    public ActionResult AuditReport(int courseId)
    {
    ViewData.Model = _reportsService.GetAuditReport(courseId);
    return View(“AuditReport”);
    }
    }

    [Test]
    public void AuditReport_WhenCalled_ItsViewDataModelShouldBeAnAuditReportViewModel()
    {
    AutoMapperBootstrapper.Bootstrap(); // Mapping between AuditReportQueryResults and AuditReportViewModel done here
    var sut = new RhinoAutoMocker();

    sut.Get().Stub(x => x.GetAuditReport(Arg.Is.Anything)).Return(new AuditReportQueryResults());

    var actionResult = sut.ClassUnderTest.AuditReport(0);

    actionResult.AssertViewRendered().WithViewData();
    }

    I get the feeling this is due to a lack of knowledge of the inner workings of ASP.NET MVC, or perhaps I’m going about the wrong way to test this, but any comments you have on the subject would be appreciated. :)

  • jrnail23

    Hi Jimmy,
    I just came across this post, and given the quickly-evolving nature of the ASP.Net MVC landscape, I thought I’d ask, is this approach something you’d still advocate for MVC 2 and 3?
    If not, what would you do differently now?

    Thanks,
    James

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @jrnail23

    Especially with the editor and display templates, yes. The question really becomes where do those view models come from. Are they projected SQL? HQL? AutoMapped from the domain model? or in the CQRS case, built from an event store? All of these options have their merits.

  • althausr

    Editor and display templates / AutoMapper : I use them and… like this, missing one only thing :
    I may have n ViewModel(s) for 1 Domain Model. If I want to use an Html.LabelFor(model => model) in my Display/EditorTemplates, I have to put a
    [DisplayName("bla")] on my ViewModel’s property : it would be nice to be able to Map the DisplayName attribute from the Model to the ViewModel(s), as the Label has no real reason to change from one view to another…

    Any idea ? Didn’t you face the problem ?

  • althausr

    Answering to myself : I could create an “abstract ViewModel class”, with all properties used in my different ViewModel-classes, and put the DisplayName Attributes on them.

    But that wouldn’t help for “flattened” properties…

  • althausr

    Hmmm. I’ll stop now, getting tired.
    Stupid auto-answer, I don’t want to have all possible properties in all my ViewModel class.

    Well, my problem remains !

  • http://twitter.com/tbehunin Todd Behunin

    In the simple case of your code:

    var product = _productRepository.GetById(id);

    What if GetById() returned an error and you want to display a user friendly error message to the user? When the mapping happens automagically through the attributes, how can I “inject” an error message? I’m assuming that the source/destination objects must have an “ErrorMessage” property? How do you handle errors/custom messages when mapping to view models in MVC using AutoMapper?

    • bartmax

      If getbyid return an error (500) or does not exist (404), you should return that HttpStatusCodes I guess. I can’t imagine a GET operation where this shouldn’t be followed. In a POST request, if you use PRG, you should have no problem at all.

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Todd

    Good question! In the first problem, there wouldn’t be an error, only that the item is null. I’d just check for that and react accordingly.

    As for mapping to view models, I’m not sure how validation could happen in that case. Typically, validation happens in a form post, which is the model binders working, not AutoMapper.

    Hope that makes sense!

  • TheCloudlessSky

    Although this post is a year and half old, this is an awesome approach and *really* reduced the fat of my controllers. I was mocking mappers… making sure map was being called… etc. It was getting way to bloated for what the controller should be focusing on. Thanks for this awesome tip!

  • http://www.ntcoding.co.uk ntcoding

    Are there any sample mvc applications I can take a look at? I’m passing my domain entities to the view – and I’m starting to feel bad.

    Cheers

  • http://blog.berkesokhan.com Berke Sökhan

    When architecting your MVC approach did you consider using an application server as an M layer?

    You could use AutoMapper at the assembler on the app server when request are made from presentation layer (V+C). Then your DTOs (looking from app srv) became ViewModel (looking from presentation server: ASP.NET MVC).

  • Pingback: ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part II » Bit Candies

  • Anonymous

    Ahh!  This rocks Jimmy, thanks a ton for your input!  I like this a whole lot better than stuffing things into ViewBag or ViewData!  Thank you!

  • M Kernbach

    Awesome article. Thanks a lot!

  • Rlcristobal

    Great job Jimmy! Ilove automapper

  • Pingback: Architecting a MVC web application with Knockout « thewayofcode

  • Pingback: MVC Attribute I Want to Keep Link For

  • Pollex

    I see this article was posted in 2009. A lot of sites link to this page, and being new to Automapper and MVC, is this article still current or does it need to be updated to reflect any new enhancements to AutoMapper of MVC?

    • Pollex

      *or MVC

    • Anonymous

      Nope, not really, the only real changes are that MVC has embraced this sort of model, with things like editor and display templates. We still build our MVC apps like this today (with dedicated view models). The only difference is our view models might be built in a number of ways, AutoMapper, SQL views, ORM projections, etc.

      • Pollex

        Great, thanks for the update.

  • Pingback: ASP.NET MVC实用技术:开篇 | Apworks.ORG

  • afzal

    [AutoMap(typeof(List), typeof(List))]
    What do I need to do for using automapper like this in MVC ???

    • jbogard

      Actually, don’t do this. Action filters, it turns out, are a bit lousy for this. Instead, create a custom action result.

  • Pingback: Messages, data and types | Jimmy Bogard's Blog

  • Trossachs

    Hi Jimmy, I’m looking to use Automapper and have followed the code snippets above but I get an error in the controller – the repository (I assume) returns an object of type Product but the return View(product) errors saying argument type Product is not assignable to type ShowProduct – because the view is expecting a ShowProduct model.

    • jbogard

      So I actually tend not to use an action filter any more, but instead a custom action result. Or, using a query object pattern if custom action result doesn’t work.

  • Pingback: How are you populating/validating your ViewModels? | Ask Programming & Technology

  • toni

    hi,
    first: thanks for the great work and explanation.

    iam a newbe to MVC at all. i struggeled around with the models/ViewModels, until i found the AutoMapper. but i have one question to it:
    is it a good idea to put the (internationalized/localized) attributes (like [Required] and [Display] and so on) to use intput validation and user friendly display? do i need to duplicate all of them in x VMs? what is your approach?

    many thanks in advance!

    greetz,
    toni

    • jbogard

      I do, but I don’t think they’re necessarily “duplicated”. I tend to build forms around activities, so there’s often only one way of mutating specific state.