我有 EF 类,我为每个类制作了具有各种 DAL 功能(获取、设置、订购等)的模型(没有从 EF poco 类继承)。BL 将在控制器内部。对于单个模型实例,一切看起来都很好,但现在我需要绑定以查看数据列表。下面是我如何做到的一个例子。我是 MVC 新手,不确定这是否是最佳实践:
该模型:
public class CustomerWishlistModel
{
static storeDataEntities db = new storeDataEntities();
//Some properties of the model
public int CustomerID { get; set; }
public int ProductID { get; set; }
public string ProductName { get; set; }
public string BrandName { get; set; }
public CustomerWishlistModel(){}
//Get wishlists by customer
public static List<CustomerWishlist> GetCustomerWishLists(int customerID)
{
return db.CustomerWishlists.Where(x => x.CustomerID == customerID).ToList();
}
//Convert wishlist to model
public static CustomerWishlistModel GetWishListModel(CustomerWishlist thisWishList)
{
CustomerWishlistModel thisWishListModel = new CustomerWishlistModel()
{
CustomerID = thisWishList.CustomerID,
ProductID = thisWishList.ProductID,
BrandName = thisWishList.Product.Supplier.BrandName,
ProductName = thisWishList.Product.Name
};
return thisWishListModel;
}
}
控制器:
[Authorize]
[HttpGet]
public ActionResult Index(string id)
{
//Get all wishlists to current customer
List<CustomerWishlist> thisWishList = CustomerWishlistModel.GetCustomerWishLists(int.Parse(id));
//Get language from url
Language thisLanguage = LanguageModel.GetLanguageByCulture(RouteData.Values["language"].ToString());
if (Session["UserID"] != null && Session["UserID"].ToString() == id && thisWishList != null && thisLanguage != null)
{
List<CustomerWishlistModel> thisWishlistModel = new List<CustomerWishlistModel>();
//Get all wishlists that their status is online and language equals to current
foreach (CustomerWishlist item in thisWishList)
{
if (item.Product.Status == (int)EnumModel.ProductStatus.Online && item.Product.LanguageID == thisLanguage.ID)
{
thisWishlistModel.Add(CustomerWishlistModel.GetWishListModel(item));
}
}
return View(thisWishlistModel);
}
else
{
return RedirectToAction("Login", "Customer");
}
}
风景:
@model IEnumerable<Store.Models.CustomerWishlistModel>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = Resources.Store.WishList;
}
@using (Html.BeginForm())
{
<h2>@Resources.Store.WishList</h2>
foreach (Store.Models.CustomerWishlistModel item in Model.ToList())
{
item.BrandName...... and other markup tags
}
}