I sent a viewdata to a view page like this.
public ActionResult SelectRes(int id)
{
var ResList = resrepository.GetAll();
ViewData["ResList"] = new SelectList(ResList, "ResId", "Res_KORNM");
return View(svcresrelationRepository.GetAll());
}
@foreach (var item in ViewData["ResList"] as List<ITSDapper.Dapper.Resource>)
{
<tr>
<td style="text-align:center;">
@Html.DisplayFor(a=> item.Res_KORNM)
</td>
</tr>
}
And I tried to display the viewdata in a view page but it's not worked. (Object reference not set to an instance of an object)
How display the viewdata in foreach statement?
You would typically use a SelectList
for data that is to be selected by a user.
If this is the intention you can just use an Html.DropDownList
:
@Html.DropDownList("SelectedId",
(IEnumerable<SelectListItem>)ViewData["ResList"])
If you are simply needing to view the data, I would change your server-side code to use something other than a SelectList
.
This could be done as follows:
Controller
public ActionResult SelectRes(int id)
{
var ResList = resrepository.GetAll();
ViewData["ResList"] = ResList;
return View(svcresrelationRepository.GetAll());
}
View
@foreach (var item in ViewData["ResList"] as List<ITSDapper.Dapper.Resource>)
{
<tr>
<td style="text-align:center;">
@Html.DisplayFor(a=> item.Res_KORNM)
</td>
</tr>
}
You are converting reference to wrong type, you are creating SelectList
instance while in View you are convering it to IList<T>
, you should convert it to SelectList
:
@foreach (var item in ViewData["ResList"] as SelectList)
{
<tr>
<td style="text-align:center;">
@Html.DisplayFor(a=> item.Text) // note this as well
</td>
</tr>
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.