路线值保持不变

时间:2012-02-20 20:48:37

标签: asp.net-mvc-3

在我的.cshtml中,我正在绘制一些数据。然后我有一个repy文本框和一个按钮,供人们回复客户服务主题。

@using (Html.BeginForm("Update", "CustomerServiceMessage", FormMethod.Post, new { id = 0 }))
    ...
}

当我提交时,当我点击我的更新动作方法时,我没有得到0,我得到了我在回复框上方绘制的父服务消息的ID。所以它就像一个电子邮件/论坛帖子,但即使我硬编码= 0,Update方法也会获得我在屏幕上绘制的父信息的ID(渲染)。

无法弄清楚原因。

1 个答案:

答案 0 :(得分:5)

  

当我提交时,我在点击我的更新操作方法时不会得到0

这是正常的,您永远不会将此ID发送到您的服务器。您刚刚使用Html.BeginForm帮助程序的wrong overload

@using (Html.BeginForm(
    "Update",                        // actionName
    "CustomerServiceMessage",        // controllerName
    FormMethod.Post,                 // method
    new { id = 0 }                   // htmlAttributes
))
{
    ...    
}

您最终获得了以下标记(假设默认路线):

<form id="0" method="post" action="/CustomerServiceMessage/Update">
    ...
</form>

看到问题?

这是correct overload

@using (Html.BeginForm(
    "Update",                        // actionName
    "CustomerServiceMessage",        // controllerName
    new { id = 0 },                  // routeValues
    FormMethod.Post,                 // method
    new { @class = "foo" }           // htmlAttributes
))
{
    ...    
}

生成(假设默认路由):

<form method="post" action="/CustomerServiceMessage/Update/0">
    ...
</form>

现在,您将在相应的控制器操作中获得id=0

顺便说一下,使用C# 4.0 named parameters可以使代码更具可读性并避免这种错误:

@using (Html.BeginForm(
    actionName: "Update", 
    controllerName: "CustomerServiceMessage", 
    routeValues: new { id = 0 }, 
    method: FormMethod.Post,
    htmlAttributes: new { @class = "foo" }
))
{
    ...    
}
相关问题