路线值保持不变

Pos*_*Guy 0 asp.net-mvc-3

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

@using (Html.BeginForm("Update", "CustomerServiceMessage", FormMethod.Post, new { id = 0 }))
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

无法弄清楚为什么.

Dar*_*rov 5

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

这是正常的,你永远不会将此ID发送到您的服务器.你刚刚使用了帮助器的错误重载Html.BeginForm:

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

你得到了以下标记(假设默认路由):

<form id="0" method="post" action="/CustomerServiceMessage/Update">
    ...
</form>
Run Code Online (Sandbox Code Playgroud)

看到问题?

这是正确的过载:

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

生成(假设默认路由):

<form method="post" action="/CustomerServiceMessage/Update/0">
    ...
</form>
Run Code Online (Sandbox Code Playgroud)

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

顺便说一下,通过使用C#4.0命名参数,您可以使代码更具可读性并避免此类错误:

@using (Html.BeginForm(
    actionName: "Update", 
    controllerName: "CustomerServiceMessage", 
    routeValues: new { id = 0 }, 
    method: FormMethod.Post,
    htmlAttributes: new { @class = "foo" }
))
{
    ...    
}
Run Code Online (Sandbox Code Playgroud)