【问题标题】:Html.ActionLink object parameters + MVC4Html.ActionLink 对象参数 + MVC4
【发布时间】:2013-06-13 07:02:18
【问题描述】:

我正在从我的视图中调用编辑操作,它应该接受一个对象作为参数。

行动:

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

}

它引发了一个异常:参数字典包含一个 null 条目,用于 'PartyWeb. Controllers.Internal.OrganizationController'。可选参数必须是引用类型、可空类型或声明为可选参数。 参数名称:参数

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

【问题讨论】:

    标签: asp.net-mvc-4 razor


    【解决方案1】:

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

    为什么要使用 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>
    

    另外请注意,我使用了嵌套的&lt;table&gt;,因为您不能在&lt;tr&gt; 中包含&lt;form&gt;,并且某些浏览器(例如 IE)不喜欢它。

    【讨论】:

    • 还有一件事,当我点击编辑按钮时,焦点不是上面提到的编辑动作,而是直接进入模型类,请您告诉我如何调用编辑动作我上面提到过?
    • +1。我不知道操作链接功能。您的帖子不仅可以帮助其他人解决特定问题,还可以帮助其他人解决基本问题。
    猜你喜欢
    • 2012-10-25
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多