Reputation: 467
I'm having a little trouble getting my head around View Models, which is tending to lead me astray and do calculations in the View it's self and therefore spaghetti code, or I fall back on ViewBag. Both of which I've heard are the incorrect way to go about things.
I've really only used database first with MVC so all my websites have a .EDMX as their Model. The code below returns an IEnumerable list of Orders, which works fine, but how should I be adding up the totals so I can display them at the end of the list? Currently I'm doing so in the foreach statement in the View.
public ActionResult SalesAll()
{
var orderproductvariants = db.OrderProductVariants.Include("Order")
.Include("ProductVariant")
.Include("ProductVariant.Product")
.Where(x => x.Order.PaidDateUtc != null)
.OrderByDescending(x => x.PriceInclTax);
return View(orderproductvariants.ToList());
}
Upvotes: 0
Views: 164
Reputation: 54636
I'd recommend creating a ViewModel for each and every view that requires any type of data.
In this case I'd create:
public class SalesAllViewModel
{
IEnumerable<OrderProductVariant> _orderProductVariant;
public SalesAllViewModel(IEnumerable<OrderProductVariant> orderProductVariant)
{
this._orderProductVariant = orderProductVariant;
}
}
Now if you need logic based on the values passed to the View, change them in the model.
public int SumOfSomethingInOrderProductVariant(int id)
{
return this._orderProductVariant
.Where(opv.ID == id)
.Sum(opv => opv.IntValue);
}
This means that logic is consistent across all data in the view. If you have multiple areas that show the same value using some logic in the view, it's very easy to forget and have to copy and paste (yeeesh) the values else where.
Using ViewBag or ViewData is typically frowned upon because no one can tell whats really going in either the controller or view, all the magic is hidden away in the View(Bag/Data).
Update 1
Please read Model–view–controller details.
A ViewModel (just model in the technically description of MVC) has nothing to do with data access. It's simply a POCO that has nothing to do with Entity Framework, or Oracle, or XML or any other data storage/retrieval technology. One of the goals behind the ViewModel is to decouple the view from the data source.
Even more confused now, is a code first approach i.e.. without a well built database???
This question has no relevance to ViewModels. Also that is a Subjective question so there isn't a good reason to answer it.
With the database i'm using I don't seem to need all the Include("Order")'s
Since you mentioned an EDMX file I can assume you're talking about Entity Framework. How you use Entity Framework is up to you. If you need to Include for performance reasons then do it, if you don't need the data it provides, don't use it. Either way it has no bearing on how a ViewModel is used in MVC.
Upvotes: 6