[英]Create Dropdown list from parents from same model
I have a Category Model in MVC model and Entity Framework, that has a self-reference relation.我在 MVC model 和实体框架中有一个类别 Model,它具有自引用关系。 That each object has a parent from the same model.
每个 object 都有一个来自相同 model 的父级。 I want to use it for categories.
我想将它用于类别。 For Example:
例如:
id | Value | Parentid
--------------------------
1 | Category1 | null
2 | Category2 | 1
3 | Category3 | null
4 | Category4 | 2
5 | Category5 | 4
how can create a dropdown list in my view for select Parent id from it?如何在我的视图中为 select 父 ID 创建下拉列表?
these is my Model Class code:这是我的 Model Class 代码:
public class CategoryModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID{ get; set; }
public int? ParentID { get; set; }
public string Value { get; set; }
public virtual CategoryModel Parent { get; set; }
public virtual ICollection<CategoryModel> Children { get; set; }
}
public class CommodityPageMap : EntityTypeConfiguration<CategoryModel>
{
public CommodityPageMap()
{
HasOptional(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentID)
.WillCascadeOnDelete(false);
}
}
First get the categories,首先获取类别,
private IEnumerable<SelectListItem> GetCategories()
{
var categories = _context.CategoryModels
.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Value
});
return categories;
}
now you pass the categories selectlist
by using ViewBag or ViewModel现在您使用
selectlist
或 ViewModel 传递类别选择列表
public ActionResult CreateCategory()
{
ViewBag.Categories = GetCategories();
return View();
}
in the view,在视图中,
<form>
<div>
<label>Category Name: </label> @Html.TextBox("CategoryName", null, new { @class = "foo" })
</div>
@if (ViewBag.Categories != null)
{
<div>
<label>Parent Category: </label>@Html.DropDownList("ParentID", new
SelectList(ViewBag.Categories, "Value", "Text"), "Select Parent
Category", new { @class = "foo" })
</div>
}
<button type="submit">Save</button></from>
If you require additional condition for categories dropdown list you can add them at GetCategories()
method.如果您需要类别下拉列表的附加条件,您可以在
GetCategories()
方法中添加它们。
As per your comment, here is a sample CategoryController
根据您的评论,这是一个示例
CategoryController
public class CategoryController : Controller
{
private ApplicationDbContext _context;
public CategoryController()
{
_context = new ApplicationDbContext();
}
[HttpGet]
public ActionResult CreateCategory()
{
ViewBag.Categories = GetCategories();
return View();
}
private IEnumerable<SelectListItem> GetCategories()
{
var categories = _context.CategoryModels
.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Value
});
return categories;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.