【发布时间】:2011-05-24 15:57:24
【问题描述】:
我有一个控制器来显示模型(用户)并想创建一个屏幕,只需一个按钮即可激活。我不想要表单中的字段。我已经在 url 中有 id。我怎样才能做到这一点?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-2 c#-4.0 http-post http-get
我有一个控制器来显示模型(用户)并想创建一个屏幕,只需一个按钮即可激活。我不想要表单中的字段。我已经在 url 中有 id。我怎样才能做到这一点?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-2 c#-4.0 http-post http-get
您可以在表单中使用隐藏字段:
<% using (Html.BeginForm()) { %>
<%= Html.HiddenFor(x => x.Id) %>
<input type="submit" value="OK" />
<% } %>
或者在表单的action中传递:
<% using (Html.BeginForm("index", "home",
new { id = RouteData.Values["id"] }, FormMethod.Post)) { %>
<input type="submit" value="OK" />
<% } %>
【讨论】:
[ActionName("Index")] 和 [HttpPost] 属性以使此操作可使用与GET 操作,或向其添加一些虚拟操作参数。
对于这种简单情况,最简单的方法是为提交按钮命名,并检查它是否有价值。 如果它有值,那么它发布动作,如果没有,那么它得到动作:
<% 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();
}
【讨论】:
在这方面有点晚了,但我找到了一个更简单的解决方案,我认为这是一个相当常见的用例,你在 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 代替 "",因为它必须是编译时常量。这是放置有趣的 cmets 以供其他人查找的好地方:)
【讨论】:
我的方法是不添加未使用的参数,因为这似乎会引起混淆,并且通常是不好的做法。相反,我所做的是将“发布”附加到我的操作名称:
public ActionResult UpdateUser(int id)
{
return View();
}
[HttpPost]
public ActionResult UpdateUserPost(int id)
{
// Do work here
RedirectToAction("ViewCustomer", new { customerID : id });
}
【讨论】:
使用 [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))
{ ... }
}
【讨论】: