2015-04-06 81 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);