2

I have this error on read my view on @foreach.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Model is null.

this is my userprofile model.

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

}

this is my control

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();
}

this is my view

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

Here are the Exception Details:

System.NullReferenceException: Object reference not set to an instance
of an object. Model is null.
1
  • I edit again my question Commented Dec 24, 2013 at 0:06

3 Answers 3

8

You're getting the NullReferenceException because you haven't passed a strongly-typed model to your view. So in your foreach loop, Model is null. The normal way of doing that is like so:

return View(model);

The real problem is that you're mixing different concepts here. You're trying to access the properties of a model in a strongly-typed way, and yet you're defining a ViewBag.Model property, which is dynamic and has no relation whatsoever to the Model property within a view.

If you want to access your model in a strongly-typed way, and that's certainly the way I'd suggest you do it, you need to make several changes. I'd suggest you first define a view model to represent the data for a 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; }
}

Now, change your action to create a list of these:

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());
    }
}

Notice that I've made several changes here. Firstly, I've added the using statement to ensure UsersContext is disposed properly. Next, I've changed the query to instantiate UserProfileViewModels, instead of anonymous types. Lastly, I'm directly passing model as a parameter to View(), making sure to call ToList() on it, in order to evaluate the query before UsersContext gets disposed.

Finally, you just need to make one change to your view:

@model List<UserProfileViewModel>

@foreach (var item in Model)
{
    // rest of code goes here
}

The @model directive specifies the exact model type that the view should expect to receive, thus making it strongly-typed.

Sign up to request clarification or add additional context in comments.

4 Comments

I do the changes but now I have this error {"Cannot implicitly convert type 'System.Collections.Generic.List<<>f__AnonymousType5<int,string,string,int,int>>' to 'Juareznlmvc.Models.UserProfile'"}
@elmona Updated my answer. Sorry, I made a mistake in the query.
John H when I add this on header table don´t read <th>@Html.DisplayNameFor(model => model.UserId)</th>
@elmona You want to use this instead: <th>@Html.DisplayNameFor(m => item.UserId)</th>.
1

Obviously - check the data types of each of the Ids that you are using to perform your joins in your database. Also ensure the database data types were mapped to the correct .Net data types.

If the data types of your ID fields appear to be ok, I would suggest narrowing down which join is causing the error. Modify you LINQ expression to have a single join and ensure there is no error. Add the other joins in one at a time until the error appears.

1 Comment

I did single join and I check all data types al all are int on my tables. not work.
0

For your model, please check that it is being populated. Depending on whatever is happening, it could be that your model is just null and possibly its type might be something that it is not expected.

-- in the controller a foreach loop on the model context reference will let you see the values

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.