1

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?

2 Answers 2

1

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>
        }
Sign up to request clarification or add additional context in comments.

4 Comments

the point is he is converting reference to wrong type, from current code it is not clear he wants a dropdown or not?
@EhsanSajjad Doesn't make sense to generate a SelectList for data from server-side though surely? Simply making the code compile is not the best answer.
@ hutchonoid : You're right. I misused the expression from used a dropdownlist. I should wrote like that;
@Roy At least your sorted now. :)
0

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>
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.