我在ASP.net MVC项目中创建了一个模型:
public class ProductListingModels:ItemEntityDataContext
{
public int ID { get; set; }
public string Name { get; set; }
public int DepartmentID { get; set; }
public int BrandID { get; set; }
}
我有一个控制器:
public class ProductListingController : Controller
{
// GET: /ProductListing/
public JsonResult Index(string depID)
{
Context DataContext = new Context();
JsonResult jr = new JsonResult();
int dep = Convert.ToInt32(depID);
var ien_item = from i in DataContext.DataContext.Items
join c in DataContext.DataContext.Categories on i.CategoryID equals c.ID
join d in DataContext.DataContext.Departments on i.DepartmentID equals d.ID
join brand in DataContext.DataContext.Brands on i.BrandID equals brand.ID
orderby i.LastUpdated descending
where i.DepartmentID == dep && i.Active > 0 && i.WebsiteShow > 0 && c.Active > 0
select i;
List<ProductListingModels> prom = new List<ProductListingModels>();
//
//Adding ien_item to the prom
//
jr.Data = prom;
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jr;
}
}
public class Context : ICEWeb.Models.ItemEntityDataContext
{
}
我想通过linq(ien_item)将我从数据库查询的每个数据添加到ProductListingModel(prom对象)的对象中, 然后将它作为json返回到我的视图中。
请有人给我一些想法。
非常感谢。
答案 0 :(得分:1)
首先,您的模型不应该继承数据上下文。将整个上下文传递给视图严重违反了对MVC至关重要的关注点分离。其次,您应该只选择视图类型的元素,然后在结果上调用ToList()。
var model = (from i in DataContext.DataContext.Items
join c in DataContext.DataContext.Categories on i.CategoryID equals c.ID
join d in DataContext.DataContext.Departments on i.DepartmentID equals d.ID
join brand in DataContext.DataContext.Brands on i.BrandID equals brand.ID
orderby i.LastUpdated descending
where i.DepartmentID == dep && i.Active > 0 && i.WebsiteShow > 0 && c.Active > 0
select new ProductListingModels
{
ID = i.ID,
Name = i.Name,
...
}).ToList();
然后使用Json()方便方法返回数据,而不是构建自己的响应。
return Json( model, JsonRequestBehavior.AllowGet );