ASP.NET MVC 4输出要查看的模型数据

时间:2014-12-03 16:15:33

标签: c# asp.net-mvc-4 razor

我当前的项目涉及为活动创建日记帐分录。我试图将有关事件的信息提取到视图中,但是我没有取得任何成功。如何在视图中获取名称和日期属性? (目前视图中没有显示这些字段。)

型号:

public class Event
{
    public int Id { get; set; }
    public string name { get; set; }
    public string location { get; set; }
    public string date { get; set; }
    public virtual ICollection<Artist> Artists { get; set; }
}

public class Journal
{
    public int Id { get; set; }
    public string JournalTitle { get; set; }
    public Event JournalEvent { get; set; }
    public string journalEntry { get; set; }
    public int Rating { get; set; }
    public UserProfile Patron { get; set; }
    public virtual ICollection<Artist> ArtistsSeen { get; set; }
}

查看:

@model EventJournal3.Models.Journal

@{
ViewBag.Title = "Details";
}
<div class="container">
    <h2>
        @Html.DisplayFor(model => model.JournalTitle)
    </h2>
    <div class="row">
        <div class="col-xs-6">
            @Html.DisplayFor(model => model.journalEntry)
        </div>
        <div class="col-xs-6">
            @Html.DisplayFor(model => model.JournalEvent.name)
            <br />
            @Html.DisplayFor(model => model.JournalEvent.date)
            <br />
            @for (int i = 1; i <= Model.Rating; i++)
            {
                <img src="~/content/star.png" height="25" width="25" />
            }
            <br />
            Artists I've Seen: <br />
            @foreach (var artist in Model.ArtistsSeen)
            {
                @artist.Name <br />
            }
        </div>
        <br />&nbsp;
    </div>

<div class="row">
    <div class="col-xs-offset-4">
        | @Html.ActionLink("Back to List", "Index") |
    </div>
</div>
</div>

控制器:

    public ActionResult Details(int id = 0)
    {
        Journal journal = db.Journals.Find(id);
        if (journal == null)
        {
            return HttpNotFound();
        }
        return View(journal);
    }

1 个答案:

答案 0 :(得分:0)

您可能必须在模型中创建一个Viewmodel,您将在视图中显示。

public class JournalEventViewModel {
   public int Id { get; set; }
   public string JournalTitle { get; set; }
   public Event JournalEvent { get; set; }
   public string journalEntry { get; set; }
   public int Rating { get; set; }
   public UserProfile Patron { get; set; }
   public string name { get; set; }
   public string location { get; set; }
   public string date { get; set; }
}

并将其交叉到您的观点。它的行为就像一个对象,所以用对象中的数据填充这个对象。您可以使用AutoMapper或映射Viewmodel本身。