Martin Boros Martin Boros - 3 months ago 8
ASP.NET (C#) Question

How do you display data from a second model in a view?

I'm trying to make a pedigree website for dogs, and I'm trying to figure out how to show data on the parents, offspring, etc. on the details page of a dog.

@model DogPedigree.Entities.Dog

@{
ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
<h4>Dog</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.AKCRegNumber)
</dt>

<dd>
@Html.DisplayFor(model => model.AKCRegNumber)
</dd>
<dt>
@Html.DisplayNameFor(model => model.name)
</dt>

<dd>
@Html.DisplayFor(model => model.name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.sex)
</dt>

<dd>
@Html.DisplayFor(model => model.sex)
</dd>

<dt>
@Html.DisplayNameFor(model => model.breed)
</dt>

<dd>
@Html.DisplayFor(model => model.breed)
</dd>

<dt>
@Html.DisplayNameFor(model => model.birthday)
</dt>

<dd>
@Html.DisplayFor(model => model.birthday)
</dd>
<dt>
@Html.DisplayNameFor(model => model.sirenumber)
</dt>

<dd>
@Html.DisplayFor(model => model.sirenumber)
</dd>
<dt>
@Html.DisplayNameFor(model => model.damnumber)
</dt>

<dd>
@Html.DisplayFor(model => model.damnumber)
</dd>

</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.AKCRegNumber }) |
@Html.ActionLink("Back to List", "Index")
</p>


So the model.AKCRegNumber is my primary key, and the sirenumber is the AKCRegNumber for the father and the damnumber is the AKCRegNumber for the mother. Any tips on how to pull some data from the parents row, like maybe displaying the name as a link to the details page for the parent? Thanks

Answer

You need a model that is wider in scope:

using DogPedigree.Entities

public class DogModel
{
    public Dog CurrentDog { get; set; }
    public Dog FatherDog { get; set; }
    public Dog MotherDog { get; set; }
    // other properties you need...
}

Fill your DogModel with whatever data you need (e.g. from the database) before you send it to the View.

You can also add a property for Title to this model...

public string Title { get; set; }

...instead of setting and retrieving from ViewBag.

In short: create the model as expansive as you need it, fill it with relevant data, then pass to the View.

Comments