Html.ActionLink对象参数+ MVC4

时间:2013-06-13 07:02:18

标签: asp.net-mvc-4 razor

我从我的视图中调用Edit动作,它应该接受一个对象作为参数。

动作:

[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>

}

它引发了一个异常:参数字典在'PartyWeb中为方法'System.Web.Mvc.ActionResult Edit(Int32)'包含非可空类型'System.Int32'的参数'id'的空条目。 Controllers.Internal.OrganizationController”。可选参数必须是引用类型,可空类型,或者声明为可选参数。 参数名称:参数

有人可以建议如何将对象作为参数传递吗?

1 个答案:

答案 0 :(得分:4)

  

有人可以建议如何将对象作为参数传递吗?

为什么使用ActionLink? ActionLink发送GET请求,而不是POST。因此,不要期望使用ActionLink调用您的[HttpPost]操作。您必须使用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)也不喜欢它。