0

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; }
}
}
2
  • 1
    Silly question, but are you sure that the Brewery property is actually being set in the Beer? That's the only reason I can see for it not to display. Commented Nov 12, 2011 at 3:59
  • You are right. When I look at the autos after beer is initialized in the details method of the beerscontroller, only the string fields are initialized. The Statement reads "Beer beer = context.Beers.find(id);" I think I need some other LINQ code to include the other properties. I'm not sure where and how to use the LINQ code Adam has suggested. Commented Nov 13, 2011 at 4:25

1 Answer 1

2

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

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

2 Comments

See the comment I wrote to competent_tech above and see if that makes any sense.
That worked! It works for including multiple objects as well. I looked into creating LINQ queries correctly instead of using the scaffolded query and that helped. Thanks.

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.