我一直在这个问题上停留了一段时间。我正在尝试从另一个表的外部表或主表中获取和显示信息。
例如,我有一个人和宠物桌。
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 是外键。
这是我的看法
@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>
}
控制器:
[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);
}
}
现在我知道上面的代码几乎没有问题,但我更担心如何显示另一个表中的信息。例如:我想在 Pets.Create 视图上显示此人的名字。我还想在 Person.Index 视图上显示 Pets.Name。
我可以在 SQL 数据库上轻松做到这一点,但我对 mvc 逻辑有点困惑。
任何帮助是极大的赞赏。