8

我有一个控制器来显示一个模型(用户),并且想创建一个屏幕,只需一个按钮即可激活。我不想要表单中的字段。我已经在 url 中有 id。我怎样才能做到这一点?

4

5 回答 5

24

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

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

[ActionName("Index"), HttpPost]
public ActionResult IndexPost(int id) { ... }

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

public ActionResult Index(int id)
{
    if (string.Equals(this.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
    { ... }
}
于 2012-11-02T14:07:36.133 回答
4

在这方面有点晚了,但我找到了一个更简单的解决方案,我认为这是一个相当常见的用例,你在 GET 上提示(“你确定你想要blah blah blah吗?”)然后使用 POST 采取行动相同的论点。

解决方案:使用可选参数。不需要任何隐藏字段等。

注意:我只在 MVC3 中测试过这个。

    public ActionResult ActivateUser(int id)
    {
        return View();
    }

    [HttpPost]
    public ActionResult ActivateUser(int id, string unusedValue = "")
    {
        if (FunctionToActivateUserWorked(id))
        {
            RedirectToAction("NextAction");
        }
        return View();
    }

最后一点,您不能使用 string.Empty 代替,""因为它必须是编译时常量。这是一个为其他人提供有趣评论的好地方:)

于 2012-05-03T19:22:58.243 回答
2

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

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

或在表单的操作中传递它:

<% using (Html.BeginForm("index", "home", 
    new { id = RouteData.Values["id"] }, FormMethod.Post)) { %>
    <input type="submit" value="OK" />
<% } %>
于 2010-12-13T13:06:30.967 回答
1

我的方法不是添加未使用的参数,因为这似乎会引起混淆,并且通常是不好的做法。相反,我所做的是将“发布”附加到我的操作名称:

public ActionResult UpdateUser(int id)
{
     return View();
}

[HttpPost]
public ActionResult UpdateUserPost(int id)
{
    // Do work here
    RedirectToAction("ViewCustomer", new { customerID : id });
}
于 2012-07-18T16:15:14.317 回答
0

对于这种简单情况,最简单的方法是为提交按钮命名,并检查它是否有价值。如果它有值,那么它 Post action,如果没有,那么它 Get action :

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

对于 Cs,您可以将 get 和 post 控制器方法合二为一:

public ActionResult Index(int? id, string btnActivate)
{
        if (!string.IsNullOrEmpty(btnActivate))
        {
            Activate(id.Value);
            return RedirectToAction("NextAction");
        }

    return View();
}
于 2010-12-13T13:49:25.690 回答