简体   繁体   English

asp.net mvc viewdata在视图页面中显示

[英]asp.net mvc viewdata display in a viewpage

I sent a viewdata to a view page like this. 我将viewdata发送到这样的视图页面。

 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? 如何在foreach语句中显示视图数据?

You would typically use a SelectList for data that is to be selected by a user. 通常,您将对用户选择的数据使用SelectList

If this is the intention you can just use an Html.DropDownList : 如果您打算这样做,则可以使用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 . 如果您只需要查看数据,则可以将服务器端代码更改为使用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 : 您正在将引用转换为错误的类型,正在创建SelectList实例,而在View中将其转换为IList<T> ,则应将其转换为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>
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM