Whenever I try the following code, my application seems to work correctly:
View: Index.cshtml
@{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3"
});
}
@Html.DropDownList("name", listItems)
But I do not want any logic for a list like this to happen in the View. Instead I would like the Controller to take care of this:
Controller: SelectionController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ExampleMVC.Controllers
{
public class SelectionController : Controller
{
// GET: Selection
public ActionResult Index()
{
//For first dropdown:
List<SelectListItem> optionList1 = new List<SelectListItem>();
optionList1.Add(new SelectListItem
{
Text = "Option 1",
Value = "Option 1"
});
optionList1.Add(new SelectListItem
{
Text = "Option 2",
Value = "Option 2"
});
optionList1.Add(new SelectListItem
{
Text = "Option 3",
Value = "Option 3"
});
//For second dropdown:
List<SelectListItem> optionList2 = new List<SelectListItem>();
optionList1.Add(new SelectListItem
{
Text = "Option 1",
Value = "Option 1"
});
optionList1.Add(new SelectListItem
{
Text = "Option 2",
Value = "Option 2"
});
optionList1.Add(new SelectListItem
{
Text = "Option 3",
Value = "Option 3"
});
List<SelectList> optionList3 = new List<SelectList>();
optionList1.Add(new SelectListItem
{
Text = "Option 4",
Value = "Option 4"
});
optionList1.Add(new SelectListItem
{
Text = "Option 5",
Value = "Option 5"
});
optionList1.Add(new SelectListItem
{
Text = "Option 6",
Value = "Option 6"
});
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3"
});
ViewBag.listItems = listItems;
ViewBag.optionList1 = optionList1;
ViewBag.optionList2 = optionList2;
ViewBag.optionList3 = optionList3;
return View();
}
}
}
Whenever I try to call the ViewBag.listItems
in my View, for example:
@Html.DropDownList("name", ViewBag.listItems)
This will return an error:
'HtmlHelper' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
How do I approach this problem?
Edit:
Using: @Html.DropDownList("name", (SelectList) ViewBag.listItems)
Will result in:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert type of System.Collections.Generic.List to System.Web.Mvc.SelectList