I have been stuck on this problem for awhile now. I am trying to get and display information from the foreign or primary table from another table.
For example, I have a person and pet table.
public class Person
{
public int id { get; set; }
// rest of the fields here
}
public class Pet
{
[DisplayName("Belongs to:")]
public int person_id { get; set; }
// Rest of the fields here
}
person_id is a foreign key.
This is my view
@model SpamValley.Models.Pet
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Pet</legend>
<div class="editor-label">
@Html.LabelFor(model => model.pet_name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.pet_name)
@Html.ValidationMessageFor(model => model.pet_name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.pet_type)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.pet_type)
@Html.ValidationMessageFor(model => model.pet_type)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.person_id, "Person")
</div>
<div class="editor-field">
@if (Model == null || Model.person_id == 0)
{
Html.DropDownList("person_id", "Select the person this pet belongs to");
}
else
{
@Html.DisplayFor(M => M.person_id);
}
@Html.ValidationMessageFor(model => model.person_id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller:
[HttpGet]
[DisplayName("Create")]
public ActionResult Create() { return Create_Get(0); }
public ActionResult Create_Get(int p_id)
{
if (p_id == 0)
{
ViewBag.person_id = new SelectList(db.People, "id", "first_name");
return View();
}
else
{
// Person Ps = db.People.ToList().Single(Per => Per.id == p_id);
// ViewBag.person_id = Ps.first_name + " " + Ps.last_name;
Pet P = new Pet { id = p_id };
return View(P);
}
}
Now I know there are few things wrong with the code above but I am more worried about how to display information from the other table. For example: I want to display First Name of the person on Pets.Create View. I would also like to display Pets.Name on Person.Index View.
I can do this easily on SQL database but I am a little confused on mvc logic for this.
Any help is greatly appreciated.