怎么会得到这样的错误

时间:2017-02-02 07:17:50

标签: asp.net-mvc asp.net-mvc-4

模型类

public partial class News
{
    public int Id { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public string Description { get; set; }
    public Nullable<bool> IsActive { get; set; }
}  public class NewsList
{
    public int Id { get; set; }
    public List<ClsNews> NewsLst { get; set; }
}  public class ClsNews
{
    public int Id { get; set; }
    public string Description { get; set; }
}

视图

                        @{int i = 1;}
                        @for (var j = 0; j < Model.NewsLst.Count; j++)
                        {
                            <tr>

                                <td>
                                    @Html.HiddenFor(m => Model.NewsLst[j].Id)
                                    @Html.HiddenFor(m => Model.NewsLst[j].Description)
                                    @Html.DisplayFor(m => Model.NewsLst[j].Description.Substring(0,20))
                                    @Html.ActionLink("Read More", "NewsInnerPage", "News")

                                </td>
                            </tr>
                            i++;
                        }
                    </table>

控制器

        News news = await db.News.FindAsync(id);
        NewsList nl = new NewsList();
        nl.Id = id;

        news.Description = (db.News.Where(h => h.Id == id)).Count() > 0 ?
                            (db.News.Where(h => h.Id == id)).First().Description : string.Empty;

        var res = db.News.Where(s => s.Id == id)
          .Select(t => new ClsNews 
          {
              Id = t.Id,
              Description = t.Description
          }).ToList();

        nl.NewsLst = res;

        if (news == null)
        {
            return HttpNotFound();
        }
        return View(nl);
    }

为什么我收到错误

  

对象引用未设置为'/'应用程序中的objectServer错误的实例。

错误发生在

行上
@for (var j = 0; j < Model.NewsLst.Count; j++) 

在视图页面中。但我在表中有数据,那我怎么得到错误?

模型类中有什么要改变来获取NewsLst中的值吗?

1 个答案:

答案 0 :(得分:-1)

尝试使用foreach而不是for循环

@foreach (var item in Model.NewsLst)
{
     <tr>
        <td>
            @Html.HiddenFor(m => item.Id)
            @Html.HiddenFor(m => item.Description)
            @Html.DisplayFor(m => item.Description.Substring(0,20))
            @Html.ActionLink("Read More", "NewsInnerPage", "News")
       </td>
     </tr>
}