0

I want to pass a nested list (List<OptionValueList>) to a View; then render each corresponding List<OptionValue> inside @Html.DropdownListFor.

Class:

public class OptionValue
{
   public int OptionID { get; set; }
   public int ValueID { get; set; }
   public string ValueName { get; set; }      
}
public class OptionValueListList : List<OptionValueList> { }
public class OptionValueList : List<OptionValue> { }   

I fill the class OptionValueListList from db, but I couldn't adapt it in SelectListItem in order to bind data to @HtmlDropdownListFor.

Below is my View:

    @model Program.Models.OptionValueListList

    @foreach (var item in Model) /*List<OptionValueList>*/
    {
         foreach (var y in item) /*List<OptionValue>*/
         {        
  @Html.DropDownListFor(m=>y.ValueID, new SelectList(@ViewBag.x, "Value", "Text"), "Option Values")
       }
     }

And below is where I try to pass data and could not bind properly as it renders same dropdownlistfor for 18 times:

   OptionValueListList o = new OptionValueListList();
   o = pr.GetOptionsForProduct(id);
   foreach (var item in o)
   {
        foreach (var i in item)
        {
             List<SelectListItem> li = new List<SelectListItem>();
             li = (from c in item
                  select new SelectListItem
                  {
                        Text = c.ValueName,
                        Value = c.ValueID.ToString()
                  }).ToList();
              ViewBag.x = li;
         }  
    }

The problem in ViewBag.x = li; Where should I put this Viewbag? Thanks.

Zeynep
  • 159
  • 1
  • 15
  • What is the error message are you receiving? Moreover its still not clear what are you expecting. – TanvirArjel Mar 15 '19 at 10:55
  • I need to pass `OptionValueListList` type to `List` list to bind dropdowns in the view. As there will be multiple dropdowns, I have a nested list of type `OptionValueListList`. I used to pass a simple list with `List` but I could not do it for 2 dimensional one. I don't get errors except it doesnt recognize my classes.. @TanvirArjel – Zeynep Mar 15 '19 at 11:53
  • Add the exact error message to the question please! – TanvirArjel Mar 15 '19 at 11:55
  • @TanvirArjel I just added the error message – Zeynep Mar 15 '19 at 12:03
  • Wait! I shall back to your soon. – TanvirArjel Mar 15 '19 at 12:06
  • Regarding your class structure which inherits from `List`, you should consider reading [this issue](https://stackoverflow.com/questions/5376203/inheriting-from-listt). Instead of inheriting from `List`, use `Collection` instead. – Tetsuya Yamamoto Mar 18 '19 at 03:30
  • I tried using Collection instead, but it still does not pass the nested lists to `SelectListItem` neighter. @TetsuyaYamamoto – Zeynep Mar 24 '19 at 18:51

0 Answers0