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:
I decided to see if I could fake out the scaffolding tool and I was able to!
Here's what you do:
- Make your POCO MyThingViewModel class.
- Make sure to have one property in the class annotated with [Key].
- Take some time to annotate your view model with attributes like:
- [StringLength(10)]
- [Required]
- [DataType(DataType.Date)]
- [Display(Name = @"Unit Type")]
- [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
- [Range(1,100)]
- Find your DbContext class and add a DbSet<MyThingViewModel>
- BUILD your solution.
- Now on the controllers folder, right click and "Add Scaffolded Item..."
- Choose MVC 5 Controller with views, using Entity Framework.
- Choose your DbContext, MyThingViewModel Class, and desired controller name like, MyThingsController.
- 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:
Now that you have your views:
- Remove the DbSet and Key attribute.
- Edit the controller to populate the View Model however you need to.
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.
Comments
Post a Comment