【发布时间】:2011-10-29 08:31:28
【问题描述】:
在查看模型的 MVC3 示例时。大多数人倾向于使用模型类来为业务对象创建类定义,以保存很少或没有逻辑的数据。那么模型的唯一目的就是传递。例如:
namespace MvcMusicStore.Models
{
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int AlbumId { get; set; }
public int Count { get; set; }
public System.DateTime DateCreated { get; set; }
public virtual Album Album { get; set; }
}
}
这就是模型类在 MVC 中的典型使用方式吗?有时我会看到逻辑,但对操作数据非常具体。例如:
public partial class ShoppingCart
{
MusicStoreEntities storeDB = new MusicStoreEntities();
string ShoppingCartId { get; set; }
public const string CartSessionKey = "CartId";
public static ShoppingCart GetCart(HttpContextBase context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
// Helper method to simplify shopping cart calls
public static ShoppingCart GetCart(Controller controller)
{
return GetCart(controller.HttpContext);
}
public void AddToCart(Album album)
{
// Get the matching cart and album instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.AlbumId == album.AlbumId);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
AlbumId = album.AlbumId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
// Save changes
storeDB.SaveChanges();
}
}
模型的正确使用方法是什么?在经典的 MVC 定义中,模型是应用程序的智能所在。但是查看 MVC3 示例,很多逻辑都在控制器或另一层中,例如数据访问。这样做有什么好处?
谢谢
【问题讨论】:
标签: asp.net-mvc-3 model