I have a Category Model in MVC model and Entity Framework, that has a self-reference relation. That each object has a parent from the same 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?
these is my Model Class code:
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
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.
As per your comment, here is a sample 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.