Wednesday, March 30, 2016

Generate .NET MVC Views for a ViewModel

So I have a ViewModel that I created.  Now I want to generate a controller and views for it with the typical CRUD actions.  I'm not going to use all the actions, but I did want a few of them.  This is very easy to do with normal Entity Framework entities, but what about a view model?

I decided to see if I could fake out the scaffolding tool and I was able to!

Here's what you do:


  1. Make your POCO MyThingViewModel class.
  2. Make sure to have one property in the class annotated with [Key].
  3. Take some time to annotate your view model with attributes like:
    1. [StringLength(10)]
    2. [Required]
    3. [DataType(DataType.Date)]
    4. [Display(Name = @"Unit Type")]
    5. [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
    6. [Range(1,100)]
  4. Find your DbContext class and add a DbSet<MyThingViewModel>
  5. BUILD your solution.
  6. Now on the controllers folder, right click and "Add Scaffolded Item..."
  7. Choose MVC 5 Controller with views, using Entity Framework.
  8. Choose your DbContext, MyThingViewModel Class, and desired controller name like, MyThingsController.
  9. Click Finish
The scaffolding tool will do its work and create the views for you!  Obviously now you have code that will not run since there is no MyThingViewModel in the database.  (Don't try to run this code with automatic migrations!)

Now that you have your views:

  1. Remove the DbSet and Key attribute.
  2. Edit the controller to populate the View Model however you need to.
Enjoy the "free" views.


Alternate Option

There is another option.  You can simply use a DB Model in the Add Scaffolded Item Wizard and manually change the code to use a view model.  This is pretty easy to do for CRUD implementations where the DB Model and the view model are almost identical.