@foreach model为null:System.NullReferenceException:未将对象引用设置为对象的实例

elm*_*ona 2 linq asp.net-mvc-4

我在阅读@foreach上的观点时遇到此错误.

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例.模型为空.

这是我的userprofile模型.

 public class UsersContext : DbContext
{

    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Secretarias> Secretarias { get; set; }
    public DbSet<Secretarias_Direcciones> Secretarias_Direcciones { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    [Required]
    public string Nombre { get; set; }
    [Required]
    public int SecretariaId { get; set; }
    [Required]
    public int DireccionId { get; set; }
    [Required]
    public string UserName { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

这是我的控制

public ActionResult ListaUsuarios()
{
    UsersContext db = new UsersContext();
    var model = from usrs in db.UserProfiles
                select new { usrs.UserId, usrs.Nombre, usrs.UserName, usrs.SecretariaId, usrs.DireccionId };
    ViewBag.Model = model.ToList();

    return View();
}
Run Code Online (Sandbox Code Playgroud)

这是我的看法

 @foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserId)
        </td>
         <td>
            @Html.DisplayFor(modelItem => item.Nombre)
        </td>
                <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
                <td>
            @Html.DisplayFor(modelItem => item.SecretariaId)
        </td>
                <td>
            @Html.DisplayFor(modelItem => item.DireccionId)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
            @Html.ActionLink("Details", "Details", new { id=item.UserId}) |
            @Html.ActionLink("Delete", "Delete", new { id=item.UserId })
        </td>
    </tr>
}
Run Code Online (Sandbox Code Playgroud)

以下是异常详细信息:

System.NullReferenceException: Object reference not set to an instance
of an object. Model is null.
Run Code Online (Sandbox Code Playgroud)

Joh*_*n H 7

你得到的是NullReferenceException因为你没有将强类型模型传递给你的视图.所以在你的foreach循环中,Modelnull.正常的做法是这样的:

return View(model);
Run Code Online (Sandbox Code Playgroud)

真正的问题是你在这里混合了不同的概念.您尝试以强类型方式访问模型的属性,但您正在定义一个ViewBag.Model属性,该属性是动态的,并且与Model视图中的属性无关.

如果你想以强类型的方式访问你的模型,这肯定是我建议你这样做的方式,你需要做一些改变.我建议你先定义一个视图模型来表示一个数据UserProfile:

public class UserProfileViewModel
{
    public int UserId { get; set; }
    public string Nombre { get; set; }
    public int SecretariaId { get; set; }
    public int DireccionId { get; set; }
    public string UserName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,更改您的操作以创建以下列表:

public ActionResult ListaUsuarios()
{
    using (UsersContext db = new UsersContext())
    {
        var model = from usrs in db.UserProfiles
                    select new UserProfileViewModel
                    {
                        UserId = usrs.UserId,
                        Nombre = usrs.Nombre,
                        UserName = usrs.UserName,
                        SecretariaId = usrs.SecretariaId,
                        DireccionId = usrs.DireccionId
                    };

        return View(model.ToList());
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我在这里做了一些更改.首先,我添加了using声明以确保UsersContext正确处理.接下来,我已经将查询更改为实例化UserProfileViewModels,而不是匿名类型.最后,我直接model作为参数传递View(),确保调用ToList()它,以便在UsersContext处理之前评估查询.

最后,您只需对视图进行一次更改:

@model List<UserProfileViewModel>

@foreach (var item in Model)
{
    // rest of code goes here
}
Run Code Online (Sandbox Code Playgroud)

@model指令指定视图应该接收的确切模型类型,从而使其强类型化.