如何创建从httpget获取相同参数的httppost?

wal*_*cir 7 asp.net-mvc http-get http-post c#-4.0 asp.net-mvc-2

我有一个控制器来显示一个模型(用户),并希望创建一个屏幕只需一个按钮来激活.我不想要表格中的字段.我已经在网址中有了id.我怎么能做到这一点?

Kna*_*ģis 19

使用[ActionName]属性 - 这样您可以让URL看起来指向相同的位置,但根据HTTP方法执行不同的操作:

[ActionName("Index"), HttpGet]
public ActionResult IndexGet(int id) { ... }

[ActionName("Index"), HttpPost]
public ActionResult IndexPost(int id) { ... }
Run Code Online (Sandbox Code Playgroud)

或者,您可以在代码中检查HTTP方法:

public ActionResult Index(int id)
{
    if (string.Equals(this.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
    { ... }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 2

您可以在表单内使用隐藏字段:

<% using (Html.BeginForm()) { %>
    <%= Html.HiddenFor(x => x.Id) %>
    <input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

或通过以下形式的操作传递:

<% using (Html.BeginForm("index", "home", 
    new { id = RouteData.Values["id"] }, FormMethod.Post)) { %>
    <input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

  • @waldecir,您有两种可能性:要么重命名您的控制器操作以使编译器满意,然后仍然使用 `[ActionName("Index")]` 和 `[HttpPost]` 属性来使该操作可以使用相同的名称访问作为 GET 操作,或者向其中添加一些虚拟操作参数。 (3认同)