Apply filtering to generate a dropdown list

老子叫甜甜 提交于 2019-11-29 08:54:30

Use the following code to generate your select list data

    public IEnumerable<SelectListItem> SelectList()
    {
        List<SelectListItem> selectList = new List<SelectListItem>();
        var listOfCat1 = db.TcSets.ToList();

        if (listOfCat1 != null)
        {
            if (listOfCat1.Count>0)
            {
                foreach (var item in listOfCat1)
                {
                    SelectListItem sVM = new SelectListItem();
                    sVM.Value = item.Id.ToString();
                    sVM.Text = item.Name;
                    selectList.Add(sVM);
                }
            }
        }

        return selectList.AsEnumerable();

    }

Then, put the following code in your controller before calling the view

    ViewBag.ProductCategoriesList = SelectList();

In your View, call the dropdown list with the following line of code

   <div class="form-group" >
      @Html.LabelFor(model => model.TcSetID , "Product Category", htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
       @Html.DropDownListFor(x => x.TcSetID , @ViewBag.ProductCategoriesList as IEnumerable<SelectListItem>, "--- Select Tc Set  ---", new { @class = "form-control", @style = "background-color:yellow;border-color:royalblue" })
          @Html.ValidationMessageFor(model => model.TcSetID , "", new { @class = "text-danger" })
      </div>
  </div>

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!