1

If I have a database and I base all my models on the database (using LINQ basically to fetch/set the data). Is it possible to only use a part of those models to create my views? Say I have three columbs in a table, and I only need two for my view, can I simply use two of the three using my database model or should I create a new model to use in my views.

And if I have to create new models, any simple way to do this? I'm using Visual Studio 2015.

Thank you

user3117628
  • 776
  • 1
  • 15
  • 35
  • [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Nov 26 '16 at 22:47

1 Answers1

1

It is common to create View Models to represent a slice of your domain model when putting data in a view.

For example you may have a BookViewModel and a BookEditModel. You could show and permit editing of different fields depending on the model.

class BookViewModel 
{
    [ReadOnly]
    public string ISBN { get; set;}
    [ReadOnly]
    public string Title { get; set;}
    [ReadOnly]
    public string Author { get; set;}
}

class BookEditModel 
{
    [ReadOnly]
    public string ISBN { get; set;}
    [Validate(...)]
    public string Title { get; set;}
    [Validate(...)]
    public string Author { get; set;}
    [ReadOnly]
    public DateTime LastUpdated {get;set;}
}

If you're looking into an easy way to create these view models, there is a tool called AutoMapper that allows you to easily map between domain and view models.

AJ X.
  • 2,729
  • 1
  • 23
  • 33
  • So basically I should be creating new view models , correct? – user3117628 Nov 26 '16 at 14:04
  • Alright, thank you! :) Will accept when I'm able to. – user3117628 Nov 26 '16 at 14:07
  • One more question: if my model is the same for both, should I create a seperate viewmodel anyway or is it fine to use that one? Would make it more structured I guess but it would mean duplicate code. – user3117628 Nov 26 '16 at 16:34
  • If it truly is 1:1 you may have "duplicate" code, but you are also gaining the flexibility of separation: Say you add 5 new columns to your database table in the future but you don't want your front end to know about them. Having your view model in place guarantees that. On the flip side: imagine your view model needs to concatenate some fields for display (ie. Name = first + middle + last). Your database model shouldn't have to know about this. In summary: As your app becomes more complex, the value of view models (and separation of concerns, in general) grows exponentially. – AJ X. Nov 26 '16 at 16:45
  • Makes alot of sense. Thanks! :) – user3117628 Nov 26 '16 at 16:54