控制器
public ActionResult brand(int brand_Id = 0)
{
var model = db.MVCs.Where(i => i.brand_Id == brand_Id);
if (model == null)
{
return HttpNotFound();
}
return View(model);
}
查看
@model MVC3.Models.productDB
@{
ViewBag.Title = "brand";
Layout = "~/Views/Shared/_LayoutPageMaster.cshtml";
}
<h2>brand</h2>
@foreach(var item in Model.brand){
@Html.DisplayFor(i=>i.ProductName)}
模型
public class productDB
{
[Key]
public int ID {get;set;}
public string ProductName { get; set; }
public string ProdactDetails { get; set; }
[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]
public decimal Price { get; set; }
[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]
public decimal? OffPrice { get; set; }
[DataType(DataType.ImageUrl)]
public string image { get; set; }
[Display(Name = "Cat")]
public int Cat_Id { get; set; }
[ForeignKey("Cat_Id")]
public virtual Cat Cat { get; set; }
public string ProdactTitle { get; set; }
[Display(Name = "brand")]
public int brand_Id { get; set; }
[ForeignKey("brand_Id")]
public virtual Brand brand { get; set; }
}
public class productDBContext : DbContext
{
public DbSet<productDB> MVCs { get; set; }
}
我想根据品牌名称对数据库进行排序,但它不起作用
错误:
传递到字典中的模型项的类型为&System; System.Data.Entity.Infrastructure.DbQuery`1 [MVC3.Models.productDB]&#39;,但此字典需要类型为&的模型项#39; MVC3.Models.productDB&#39;
答案 0 :(得分:1)
编辑您的控制器:
public ActionResult brand(int brand_Id = 0)
{
var model = db.MVCs.Where(i => i.brand_Id == brand_Id).OrderBy(b => b.Brand.Brand_name).ToList();
if (model == null)
{
return HttpNotFound();
}
return View(model);
}
您也可以使用OrderByDescending()。
有关ToList()
的更多信息:msdn
答案 1 :(得分:0)
在进行查询时,您只需在您的产品系列上调用.OrderBy(x => x.Brand.Brand_name)