2015-04-06 82 views
1

我是MVC的新手,所以请原谅我的noobie问题。我从字面上有一个Person对象/类和一个Child对象/类。无法创建MVC子项

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视图。我想我需要'传递'父键到AddChild视图,但我无法让它工作。我的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

'ActionLink'将指向'[HTTPGET] AddChild'方法等方面存在应该是该方法的'int id'参数。但是,您只显示了[HttpPost]方法。应该有一个'[HttpGet] AddChild'方法。 – AaronLS

+0

Yes:// GET:Children/Create public ActionResult Create(int?id) { return View(); } –

+0

我不知道要在这里放置什么来设置ParentKey –

回答

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 }); 
} 

通过填充子模型的此属性,并将它传递给View(它使它在AddChild中可用。 cshtml视图。在您的形式应该有可能是形式的身体内声明的,这样节省当这个值被公布的隐藏字段:

Html.HiddenFor(m=>m.ParentKey);