在MVC视图中显示存储过程的结果(EF 5 / MVC 4)
本文关键字:MVC EF 视图 显示 存储过程 结果 | 更新日期: 2023-09-27 18:18:16
目标
我想在我的视图中显示存储过程的结果。
实体框架自动为我导入了一个执行过程的方法,但是我没有得到我期望在屏幕上显示的结果。
导入的函数为:
public virtual ObjectResult<getProductsListForHome_Result> getProductsListForHome(Nullable<int> inOffer, Nullable<int> categoryId)
{
var inOfferParameter = inOffer.HasValue ?
new ObjectParameter("inOffer", inOffer) :
new ObjectParameter("inOffer", typeof(int));
var categoryIdParameter = categoryId.HasValue ?
new ObjectParameter("categoryId", categoryId) :
new ObjectParameter("categoryId", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<getProductsListForHome_Result>("getProductsListForHome", inOfferParameter, categoryIdParameter);
}
我已经尝试过的
在ProductsController:
//
// GET: /Products/
public ActionResult Index()
{
ObjectResult<getProductsListForHome_Result> products = db.getProductsListForHome(1, 14);
return View(products.ToList());
}
使用前面的代码,当我访问http://myapp.com/Products/
时,我得到以下消息:
传入字典的模型项类型为'System.Collections.Generic.List
1[MyApp.Models.getProductsListForHome_Result]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1[MyApp.Models.bm_products]'.
我该怎么做才能解决这个问题?
第一个问题写得好!
这是一个类型转换问题,看起来你的答案是这里可以接受的答案:
MVC:传入字典的模型项是X类型的,但是这个字典需要一个X类型的模型项
很可能你的视图是强类型的,它被声明为
@model System.Collections.Generic.IEnumerable<MyApp.Models.bm_products>
然而,你在控制器中传递了不同的类型,并且遇到了错误。
你能做的:
为视图指定另一种类型。视图本身可能需要一些重构:
@model System.Collections.Generic.IEnumerable<MyApp.Models.getProductsListForHome_Result>
优先。在控制器中运行一些代码,将从SP返回的集合转换为视图可以使用的内容:
public ActionResult Index() { ObjectResult<getProductsListForHome_Result> products = db.getProductsListForHome(1, 14); List<bm_products> viewProducts = products.Select(p => new bm_products{ProductName = p.Name, ProductPrice = p.Price}).ToList(); return View(viewProducts); }