1

I am trying to display the name of an author of a question but unlike the other properties of the model, the ApplicationUser.UserName property does not show in the view (it's just blank). I am using Entity Framework, MVC 5 and Razor.

My Question model:

public class Question { public int QuestionID { get; set; } public string Title { get; set; } public ApplicationUser Author { get; set; } public string Description { get; set; } [DisplayName("Created")] public DateTime CreationDateTime { get; set; } public int Rating { get; set; } } 

My QuestionController Index action:

// GET: Questions public ActionResult Index() { return View(db.Questions.ToList()); } 

And the view:

@model IEnumerable<Waegogi.Models.Question> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th> @Html.DisplayNameFor(model => model.Author.UserName) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.CreationDateTime) </th> <th> @Html.DisplayNameFor(model => model.Rating) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.Author.UserName) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.CreationDateTime) </td> <td> @Html.DisplayFor(modelItem => item.Rating) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.QuestionID }) | @Html.ActionLink("Details", "Details", new { id=item.QuestionID }) | @Html.ActionLink("Delete", "Delete", new { id=item.QuestionID }) </td> </tr> } </table> 

Where am I going wrong?

3
  • may be you need applicationUser imports? and also instansiation of that class ? Commented Oct 4, 2014 at 11:31
  • Are you fetching Question through an ORM like nHibernate? It could be lazy lading the related property. Commented Oct 4, 2014 at 11:37
  • I'm using Entity Framework, I have little experience with it. Commented Oct 4, 2014 at 11:57

1 Answer 1

2

You should be able to solve this by explicitly loading your relationships in your controller call:

public ActionResult Index() { return View(db.Questions.Include(q => q.ApplicationUser).ToList()); } 
Sign up to request clarification or add additional context in comments.

1 Comment

This solved my problem. The problem was my ignorance regarding lazy loading.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.