2013-06-13 23 views
0

我從我的視圖中調用了Edit action,它應該接受一個對象作爲參數。Html.ActionLink對象參數+ MVC4

操作:

[HttpPost] 
    public ActionResult Edit(Organization obj) 
    { 
     //remove the lock since it is not required for inserts 
     if (ModelState.IsValid) 
     { 
      OrganizationRepo.Update(obj); 
      UnitOfWork.Save(); 
      LockSvc.Unlock(obj); 
      return RedirectToAction("List"); 
     } 
     else 
     { 
      return View(); 
     } 
    } 

從視野:

@foreach (var item in Model) { 

cap = item.GetValForProp<string>("Caption"); 
nameinuse = item.GetValForProp<string>("NameInUse"); 
desc = item.GetValForProp<string>("Description"); 

<tr> 
    <td class="txt"> 
     <input type="text" name="Caption" class="txt" value="@cap"/> 
    </td> 
    <td> 
     <input type="text" name="NameInUse" class="txt" value="@nameinuse"/> 
    </td> 
    <td> 
     <input type="text" name="Description" class="txt" value="@desc"/> 
    </td> 
    <td> 
     @Html.ActionLink("Edit", "Edit", "Organization", new { obj = item as Organization }, null) 
    </td> 
</tr> 

}

它拋出一個異常:參數字典包含的非空的參數 'ID' 無效項在'PartyWeb.Controllers.Internal.OrganizationController'中爲方法'System.Web.Mvc.ActionResult Edit(Int32)'鍵入'System.Int32'。可選參數必須是引用類型,可爲空類型,或者聲明爲可選參數。 參數名稱:參數

有人可以建議如何傳遞對象作爲參數嗎?

回答

4

有人可以建議如何傳遞對象作爲參數嗎?

爲什麼使用ActionLink? ActionLink發送GET請求,而不是POST。所以不要指望您的[HttpPost]行爲可以通過使用ActionLink來調用。您將不得不使用HTML表單幷包含您想要作爲輸入字段發送的所有屬性。

所以:

<tr> 
    <td colspan="4"> 
     @using (Html.BeginForm("Edit", "Organization", FormMethod.Post)) 
     { 
      <table> 
       <tr> 
       @foreach (var item in Model) 
       { 
        <td class="txt"> 
         @Html.TextBox("Caption", item.GetValForProp<string>("Caption"), new { @class = "txt" }) 
        </td> 
        <td class="txt"> 
         @Html.TextBox("NameInUse", item.GetValForProp<string>("NameInUse"), new { @class = "txt" }) 
        </td> 
        <td class="txt"> 
         @Html.TextBox("Description", item.GetValForProp<string>("Description"), new { @class = "txt" }) 
        </td> 
        <td> 
         <button type="submit">Edit</button> 
        </td> 
       } 
       </tr> 
      </table> 
     } 
    </td> 
</tr> 

還要注意,我用了一個嵌套<table>,因爲你不能有一個<form><tr>一些瀏覽器如IE裏面會不喜歡它。

+0

謝謝。我忽略了ActionLink,總是感到困惑。 – mmssaann

+0

還有一件事,當我點擊編輯按鈕時,重點不會編輯上面提到的動作,它直接進入模型類,請問如何調用上面提到的編輯動作? – mmssaann

+0

+1。我不知道動作鏈接功能。您的帖子不僅可以幫助其他人解決特定問題,還可以解決基本問題。 – wuhcwdc