将ApplicationUser的UserName放入视图中

时间:2014-10-04 11:30:16

标签: c# entity-framework asp.net-mvc-5

我正在尝试显示问题作者的姓名,但与模型的其他属性不同,ApplicationUser.UserName属性不会显示在视图中(它只是空白)。我正在使用Entity Framework,MVC 5和Razor。

我的问题型号:

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

我的 QuestionController 索引操作:

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

观点:

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

我哪里错了?

1 个答案:

答案 0 :(得分:1)

您应该可以通过在控制器调用中明确加载关系来解决此问题:

public ActionResult Index()
{
     return View(db.Questions.Include(q => q.ApplicationUser).ToList());
}