travis1097
travis1097

Reputation: 2949

Accessing objects inside model passed to Razor View in ASP.NET MVC 3

My beer model has a brewery object but I can't access the brewery's properties when I'm in the view. Intellisense seems to think I can access the brewery property but the DisplayFor method doesn't print anything.

@model BeerRecommender.Models.Beer

@{
ViewBag.Title = "Details";
}

<h2>@Html.DisplayFor(model => model.Name)</h2>

<fieldset>
<legend>Details</legend>

<div class="display-label">Style: @Html.DisplayFor(model => model.Style.Name)</div>
<div class="display-label">Brewery: @Html.DisplayFor(model => model.Brewery.Name)</div>

</fieldset>

Here is the Beer class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using BeerRecommender.Models.ViewModels;

namespace BeerRecommender.Models
{
public class Beer
{
    [Key]
    public int BeerID { get; set; }

    public ICollection<City> Cities { get; set; }

    public ICollection<Tag> Tags { get; set; }

    public Style Style { get; set; }

    public string Name { get; set; }

    public Brewery Brewery { get; set; }
}

...and here is the Brewery class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace BeerRecommender.Models
{
public class Brewery
{
    [Key]
    public int BreweryID { get; set; }

    public string Name { get; set; }

    public ICollection<Beer> Beers { get; set; }

    public City City { get; set; }
}
}

Upvotes: 0

Views: 3550

Answers (1)

Adam Tuliper
Adam Tuliper

Reputation: 30162

How are you loading the Beer class? If this is from say entity framework you will need to call .Include(o=>o.Brewery) in your loading code to include that table . This is assuming EF 4.1 otherwise you need the string name like .Include("Brewery") if in 4.0

Upvotes: 2

Related Questions