Reputation: 194
can someone help me in the following code, it does not display anything on view
List<string> oo = ViewBag.oox;
IEnumerable<SelectListItem> obj = new List<SelectListItem>(oo.Select(ch => new SelectListItem { Text = ch, Value = ch }));
Html.DropDownList("xyz", obj);
foreach (var item in obj)
{
@item.Value
}
Upvotes: 0
Views: 62
Reputation: 218722
Assuming ViewBag.oox
has a list of string in it, you should call the DropDownList
method outside of your code block.
Also you do not need the explicit List<string>
constructor (not a cause for your dropdown not rendering thougg). The Select
method returns an IEnumerable and you can use that for the helper method call.
@{
List<string> oo = ViewBag.oox;
var obj = oo.Select(ch => new SelectListItem { Text = ch, Value = ch });
}
@Html.DropDownList("xyz", obj)
The DropDownList
method returns a MvcHtmlString
for the SELECT element markup. When you call it inside the code block, you are not using the output of the method anywhere. When you make the call outside of the code block with @
prefix, razor will use the output (HTML markup) and use that to render that specific part of the page.
So if you absolutely want to call the method inside the code block just out of curiosity. you can store the result of the method call and use that outside to render it.
@{
List<string> oo = ViewBag.oox;
var obj = oo.Select(ch => new SelectListItem { Text = ch, Value = ch });
MvcHtmlString selectMarkup = Html.DropDownList("xyz", obj);
}
@selectMarkup
Ideally, you should follow the first approach, calling the method outside of your code block.
Keep in mind that, If ViewBag.oox
returns an unexpected value, your code will crash when calling the Select
method on that. So it is safe to do a null check before using it. Consider using a strongly typed view model approach instead of ViewBag/ViewData to transfer this data.
Upvotes: 1
Reputation: 24957
You're adding List<SelectListItem>
inside other new List<SelectListItem>
instance in this code below, it is the primary cause why the items are not displayed:
IEnumerable<SelectListItem> obj = new List<SelectListItem>(oo.Select(ch => new SelectListItem { Text = ch, Value = ch }));
The correct way is directly using Select
like this:
@{
List<string> oo = ViewBag.oox;
List<SelectListItem> obj = oo.Select(ch => new SelectListItem { Text = ch, Value = ch });
}
And then use it in DropDownList
or DropDownListFor
:
@Html.DropDownList("xyz", obj);
@Html.DropDownListFor(m => m.xyz, obj);
Upvotes: 1