-1

I'm working on a simple project where I have data in two tables that I need to return to my View from my controller. I'm aware of two methods to do this in .NET, the first is create a model class, add the properties you need to access in your view, essentially creating a ViewModel. Like so:

    public class BeerListViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string BrewerName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string WebUrl { get; set; }
    public string ImageUrl { get; set; }
    public double AlcoholContent { get; set; }
    public string BeerType { get; set; }
    public int Calories { get; set; }
    public double Carbs { get; set; }
    public string Notes { get; set; }
    public int CountofReviews { get; set; }
}

Then set your model to a LINQ statement selecting the DbSet and instantiating the ViewModel and load it with the properties you need to send to the view, then return your model to the View, Like so:

//1. Instantiate the db
    OdeToBeerDb _db = new OdeToBeerDb();

    // GET: Reviews
    public ActionResult Index()
    {
        var model = from b in _db.Beers
                    orderby b.Name ascending
                    select new BeerListViewModel
                    {
                        Id = b.Id,
                        Name = b.Name,
                        BrewerName = b.BrewerName,
                        BeerType = b.BeerType,
                        ImageUrl = b.ImageUrl,
                        City = b.City,
                        Notes = b.Notes,
                        AlcoholContent = b.AlcoholContent
                    };

        return View(model);
    }

With the other method, you simply join the two tables in the LINQ query, select the properties you need to send to the View in the anonymous object and return the view, like so:

public class ReviewsController : Controller
{
    //1. Instantiate the db
    OdeToBeerDb _db = new OdeToBeerDb();

    // GET: Reviews
    public ActionResult Index()
    {
        var model = from b in _db.Beers
                    join r in _db.Reviews on b.Id equals r.BeerId
                    orderby b.Name ascending
                    select new
                    {
                        Id = b.Id,
                        Name = b.Name,
                        BrewerName = b.BrewerName,
                        BeerType = b.BeerType,
                        ImageUrl = b.ImageUrl,
                        City = b.City,
                        Notes = b.Notes,
                        AlcoholContent = b.AlcoholContent
                    };

        return View(model);
    }

What I'm wondering is: Why would I bother creating a ViewModel, copying and pasting the properties from my other classes into it, and instantiating the ViewModel? It seems kind of redundant to do that vs. just joining the tables, or is there some advantage that I am missing? And yes, I know that it is strongly typed and creating the ViewModel names the object but I have to add the properites to that class anyway, so what difference does it make if I add them to the class or the controller? For that matter, is there some equivalent to SELECT * in LINQ? Then, I wouldn't have to add the properties to the controller every time I change my model.

Katherine
  • 3,318
  • 1
  • 13
  • 17
  • 1
    i get what you saying, been there before, but try to think about it like so.... maybe it helps maybe it doesn't. instead of creating ViewModel properties for every property instead include the DB class in the ViewModel. that way the view model is just a container. You db access is meant to be tiered, i.e. not be in the controller...anyway.. Lets say in the view your showing 'Beers' create viewmodel BeersIndexViewmodel include a property List Beers when you populate it, tell EF to "include" Reviews. then your done. none of the mess you have above. – Seabizkit Aug 20 '17 at 06:37
  • This is already answered here https://stackoverflow.com/questions/4878937/why-should-i-use-view-models. It looks redundant, but in the end this brings multiple advantages mentioned there. – Turo Aug 20 '17 at 07:39
  • Helpful meta feedback: I just flagged a comment here about downvoting being an example of cyber-bulling, and it auto-deleted (there is an unpublished algorithm that means some comments will auto-delete when flagged). I've also removed some meta-commentary about voting and tone from another question. – halfer Jun 23 '19 at 20:18
  • 1
    In general, if you have an expectation of robust responses on Stack Overflow, it is best not to comment upon it beforehand. This is mainly because doing so can paradoxically be the cause of the robust responses, and thus it invites the very thing you were trying to avoid. That's unfortunate, but trying to police this human phenomena is probably futile. In any case, we would rather posts did not carry irrelevant meta-commentary anyway - most readers of Stack Overflow do not have an account and do not sign in, and they just want to read succinct and clear material. – halfer Jun 23 '19 at 20:23
  • 1
    When posting questions, it is very helpful from a psychological point of view to be open to any form of voting on it, including close voting and down voting. That someone took the time to help curate the site with these actions is generally laudable - it is why Stack Overflow is regarded as one of the highest quality tech Q&A sites in the world at present. Broadly, I don't think downvotes are worth commenting on - they are anonymous, so asking why they were made is not worth the time anyway, since the voter will have moved on. If they had wanted to offer comment feedback, they would have done. – halfer Jun 23 '19 at 20:27
  • If you get a lot of downvotes then you can always ask someone in the comments for their guesses/feedback - perhaps they will know something about the posting guidelines that you do not. However, if you get just one, just brush the dust off your shoulder and get back on the horse! One on its own doesn't mean very much, especially if the voter did not explain it. Good luck `:=)` – halfer Jun 23 '19 at 20:29

1 Answers1

2

Take a look at some problem in passing Anonymous Type in the view:

1.Create a controller that will pass an anonymous types.

    public ActionResult Index()
    {
        return View(new { TestProperties="This is a test properties."});
    }

2. Check if data is sent in the View.

@Model

3. Now let's access the properties of the anonymous type that we sent in our view.

@Model.TestProperties

Accessing the properties of the anonymous type we will encounter this error: enter image description here

Now let's create a POCO class for the ViewModel.

  1. Create a POCO class for the ViewModel. enter image description here
  2. Access the properties of the ViewModel.

enter image description here

Now the value of the ViewModel can be access and create textbox using Razor Syntax.