0

相關崗位:Populating a select box in a form using related ID in MVC3MVC3填充「創建」信息查看相關對象

我有使用MVC3和ADO.NET LINQ到實體生成的列表視圖。

我已經能夠創建一個簡單的列表視圖,用「創建」&「編輯」動作鏈接命令創建一個「相關對象」。

@Html.ActionLink("Create Shipping Profile", "../PrintProfile/Create", new { id = item.ProductId }) | 
@Html.ActionLink("Edit Shipping Profile", "../PrintProfile/Edit", new { id = item.ProductId }) 

當我創建「PrintProfile」我想要的「創建」視圖是「預填充」與「產品編號」(這是數據庫表關係),這樣我可以創建配置文件,並編輯列表中每個項目的關聯配置文件。

這裏是爲PrintProfile創建控制器

public ActionResult Create(int ProductId) 
    { 
     var entities = new CS_ShippingProfiles(); 
     entities.ProductId = ProductId; // Assign the ProductId I want to 'create' 
     return View(entities); 
    } 

    [HttpPost] 
    public ActionResult Create(CS_ShippingProfiles Profile) 
    { 
     if (ModelState.IsValid) 
     { 
      var entities = new LabelServiceEntities(); 
      entities.AddToCS_ShippingProfiles(Profile); 
      entities.SaveChanges(); 

      return Redirect("/Products"); 
     } 
     return View(Profile); 
    } 

但是當我按照鏈接,我得到一個「空」的參數異常!我究竟做錯了什麼?!

回答

1

Create行動你的動作參數被稱爲ProductId所以一定要確保你生成正確的鏈接:

@Html.ActionLink(
    "Create Shipping Profile", 
    "Create", 
    "PrintProfile", 
    new { ProductId = item.ProductId }, 
    null 
) 
| 
@Html.ActionLink(
    "Edit Shipping Profile", 
    "Edit", 
    "PrintProfile", 
    new { ProductId = item.ProductId }, 
    null 
) 

還要注意如何控制和動作被指定的,而不是爲你做(../PrintProfile/Create)使用一些相對URL。

+0

好東西!謝謝!像魅力一樣工作 - 希望這可以幫助未來的人。 – 2011-02-04 19:42:27