我是MVC的新手,所以请原谅我的noobie问题。我确实有一个Person对象/类和一个Child对象/类。
public partial class Person
{
public Person()
{
this.Registrations = new HashSet<Registration>();
this.Children = new HashSet<Child>();
}
public int PKey { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int StateKey { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public virtual State State { get; set; }
public virtual ICollection<Registration> Registrations { get; set; }
public virtual ICollection<Child> Children { get; set; }
public partial class Child
{
public int PKey { get; set; }
public int ParentKey { get; set; }
public string Name { get; set; }
public System.DateTime BirthDate { get; set; }
public virtual Person Person { get; set; }
}
我已经成功创建了一个显示该人的孩子的视图(Children.cshtml):
@foreach (var item in Model.Children)
{
<div class="form-group">
<div class="col-sm-3"> @item.Name </div>
<div class="col-sm-3"> @item.BirthDate.ToShortDateString()</div>
<div class="col-sm-3"> @Html.ActionLink("Remove", "RemoveChild", new { id = @item.PKey, parentKey = Model.PKey })</div>
</div>
}
@Html.ActionLink("Add Child to Registration", "AddChild", new { id = Model.PKey })
但是,我在尝试创建AddChild视图时感到困惑/困惑。我想我需要通过&#39; AddChild视图的Parent键,但我无法使其工作。我的AddChild视图顶部有@model NRMS.Models.Child。我的控制器中的ActionResult看起来像:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddChild([Bind(Include = "PKey,ParentKey,Name,BirthDate")] Child child)
{
if (ModelState.IsValid)
{
db.Children.Add(child);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
我假设我完全错过了某个地方的船。任何帮助将不胜感激。感谢。
BJ
答案 0 :(得分:1)
关键部分首先是此处new { id =
的属性名称:
@Html.ActionLink("Add Child to Registration", "AddChild", new { id = Model.PKey })
哪个应匹配GET方法中的参数,以及我们可以通过子模型传递的参数:
[HttpGet]
public ActionResult AddChild(int? id)
{
return View(new Child{ ParentKey = id });
}
通过填充Child模型的此属性,并将其传递给View(
,它使其在AddChild.cshtml视图中可用。在您的表单中,应该在表单的主体内声明一个隐藏字段,以便在保存时发布此值:
Html.HiddenFor(m=>m.ParentKey);