简体   繁体   English

单个Dropdownlistfor中的类别和子类别-MVC剃刀

[英]Category and Sub Category in single Dropdownlistfor - MVC Razor

I have a table with Category Id and Parent Category Id. 我有一个带有类别ID和父类别ID的表。

Category Id    Category Name   Parent Category Id
     1           Desktop              0
     2           PC                   1
     3           Mac                  1

How do I return it in a dropdownlist in the below format: 如何以以下格式在下拉列表中返回它:

在此处输入图片说明

hi buddy i looked for this much and i couldn't find it but finally i coded it myself. 嗨,哥们,我找了这么多东西,但找不到,但最后我自己编码了。

i will try to tell you how i solved this problem and works great just like ur screenshot. 我会尽力告诉您我是如何解决此问题的,就像您的屏幕截图一样,效果很好。 here is my secreenshot 这是我的秘密镜头

here is my category model it is almost same with ur model 这是我的类别模型,与您的模型几乎相同

 public class Category { public int ID { get; set; } public string CategoryName { get; set; } public int? ParentID { get; set; } [ForeignKey("ParentID")] public virtual ICollection<Category> SubCategories { get; set; } } 

then i created a View category model like this 然后我创建了一个这样的View类别模型

  public class ViewModelCategory { public Category Category { get; set; } public List<SelectListItem> Categories { get; set; } public List<SelectListItem> ChildCategories { get; set; } public List<SelectListItem> AllCategories { get { List<SelectListItem> sli = new List<SelectListItem>(); foreach (SelectListItem item in Categories) { sli.Add(item); } foreach (SelectListItem item in ChildCategories) { int i = item.Text.IndexOf(">"); string text = item.Text.Substring(0, i-1); foreach (SelectListItem listItem in ChildCategories) { int k = listItem.Text.LastIndexOf(">"); string text2 = listItem.Text.Substring(k+1); if (text2.Contains(text)) { item.Text = listItem.Text + " > " + item.Text.Substring(i+2); } } sli.Add(item); } return sli; } } } 

my codes can look like little complicate but is is not actually. 我的代码看起来有点复杂,但实际上并非如此。

there are something important in my ViewModelCategory model when u look at the model u will see 3 selectlistitem properties. 当您查看模型时,ViewModelCategory模型中有一些重要的内容,您将看到3个selectlistitem属性。 i wanna talk about these first. 我想先谈这些。

i created one of them called as "Categories" for main categories that has no any parent id value. 我为没有任何父ID值的主要类别创建了一个称为“类别”的类别。 second of them called as "ChildCategories" contains only subcategories that has parent id value 其中第二个称为“ ChildCategories”,仅包含具有父ID值的子类别

when u look at he controller codes u will see already. 当您查看控制器代码时,您将已经看到。

and the last one of called as "AllCategories". 最后一个称为“ AllCategories”。 this one is the important one couse i merged all categories in this property to send categories to dropdownlisfor in controller's view. 这是重要的一个原因,我合并了此属性中的所有类别,以将类别发送到控制器视图中的dropdownlisfor。 but it is not just for this i also did something important in this property while i merged them when u look at the loops u will see it. 但是不仅仅因为这个,我还在此属性中做了一些重要的事情,当我将它们合并时,当您查看循环时,您会看到它。 i used loops to place categories to their parents 我用循环将类别放置给他们的父母

then used my ViewModelCategory model in controller like this 然后像这样在控制器中使用ViewModelCategory模型

 ViewModelCategory vmc = new ViewModelCategory { Category = category, Categories = _businessCategories.GetItems().Where(x => x.ParentID == null).Select(x => new SelectListItem { Text = x.CategoryName, Value = x.ID.ToString() }).ToList(), ChildCategories = _businessCategories.GetItems().Where(x=>x.ParentID != null).Select(x => new SelectListItem { Text = _businessCategories.GetItems().Where(a => a.ID == x.ParentID).FirstOrDefault().CategoryName + " > " + x.CategoryName, Value = x.ID.ToString() }).ToList(), }; 

and finally i welcomed my datas from view like this 最后我从这样的角度欢迎我的数据

 <div class="form-group"> <label class="col-sm-4 control-label">Sub Category</label> <div class="col-sm-8"> @Html.DropDownListFor(model => model.Category.ParentID, Model.AllCategories.OrderBy(x=>x.Text), "Select Category", new {@class = "form-control"}) @Html.ValidationMessageFor(model => model.Category.ParentID) </div> </div> 

hope u will like this have a nice day 希望你会过得愉快

The best thing I can think of would be to create some class that hold the Name and Value for a drop down list and use it to create a SelectList in your Action. 我能想到的最好的办法是创建一个类,其中包含一个下拉列表的名称和值,并使用它在您的Action中创建SelectList。

public class SelectListValue{
  public string Text {get;set;}
  public string Value {get;set;}
}

public ActionResult SomeActionMethod()
{
  var categories = GetCategories() //Get your list of categories
  var selectListItems = new List<SelectListValue>();

  foreach(var item in categories)
  {
    var text = GetCategoryDisplay() //You will need to figure out how to generate the text, like Components > Web Cameras. This doesn't need to be a method. It could be a property on the Category object.

    selectListItems.Add(new SelectListValue {Text = text, Value = item.CategoryId.ToString()});
  }

  ViewData["CategoryList"] = new SelectList(selectListItems, "Value", "Text");
}

You will need to have a way somewhere, probably in your model, to take generate the name string. 您可能需要在模型中的某个地方找到生成名称字符串的方法。 I am guessing you are already doing that. 我猜您已经在这样做了。 Then in your view you would do something like 然后在您看来,您将执行以下操作

 @Html.DropDownListFor(x => x.CategoryId, ViewData["CategoryList"] as SelectList)

This should work, or at least something like it. 这应该起作用,或者至少是类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM