Linq 如何从MVC4下拉列表中选择的数据库中检索行
我想,如果用户从下拉列表中选择一个项目,数据库中包含的所有行都将显示该项目。有没有关于如何使用LINQ查询检索数据的建议 这是我的模型课Linq 如何从MVC4下拉列表中选择的数据库中检索行,linq,asp.net-mvc-4,sql-server-2012,Linq,Asp.net Mvc 4,Sql Server 2012,我想,如果用户从下拉列表中选择一个项目,数据库中包含的所有行都将显示该项目。有没有关于如何使用LINQ查询检索数据的建议 这是我的模型课 public class Category { public int Id { get; set; } public string CategoryName { get; set; } public string Description { get; set; } public virtual ICollection<
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public virtual ICollection<Category> Categories { get; set; } //
}
这是我的控制器
public ActionResult Create()
{
//will contain the list of CategorytNames and it will bind this on the Create.
//cshtml view as given below
ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName");
return View();
}
public ActionResult Edit(int id = 0)
{
FoodMenuItem foodmenuitem = db.FoodMenuItems.Find(id);
if (foodmenuitem == null)
{
return HttpNotFound();
}
//checking what the selected value was using LINQ query and then using that value inside SelectList.
//Now, DropDownList will look at the provided default selected value and displays it
int selected = (from cat in db.FoodMenuItems
where cat.ID == id
select cat.CategoryID).First();
ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName", selected);
// ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName", foodmenuitem.CategoryID);
return View(foodmenuitem);
}
你的代码完全正确。在视图中添加以下代码
@Html.DropDownList("CategoryID ","--Select Category--")
请试试这个。如果它不起作用,请告诉我,我会为这个问题找到一个新的解决方案。您应该使用ajax来解决这个问题。处理dropdownlist的.change事件,将所选值传递给控制器,并根据类别返回部分视图,然后更新DOM。
@Html.DropDownList("CategoryID ","--Select Category--")