【问题标题】:ASP.net MVC Can you overload an Index() HttpPost?ASP.net MVC 你能重载一个 Index() HttpPost 吗?
【发布时间】:2013-09-23 21:07:11
【问题描述】:

假设我有一个包含 2 个表单的页面,它们都在同一页面上提交不同的数据,一个提交两个 ID,另一个只提交一个 ID。他们都回发到同一页面(本身)。这是 HTML 的样子...

<form method="post">

<select name="regID">
...
</select>

<select name="jobID">
...
</select>

<input type="submit" value="Add">

</form>

<form method="post">

<button name="ID" type="submit" value="@ID">Remove</button>    

</form>

现在,我可以在控制器中处理第一个表单

 [HttpPost]
 public ActionResult Index(int regID, int jobID)
 {
 ....
 }

但是,如果我尝试通过添加

来处理第二种形式
 [HttpPost]
 public ActionResult Index(int ID)
 {
 ....
 }

当我点击提交按钮时,我现在会得到错误

The current request for action 'Index' on controller type 'UserJobController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(Int32) on type careerninja.Controllers.UserJobController
System.Web.Mvc.ActionResult Index(Int32, Int32) on type careerninja.Controllers.UserJobController 

那么,是否可以在控制器中重载具有不同值的 [HttpPost] 方法来处理 2 组不同的表单数据,或者这不可能?是否有另一种解决方案我可能无法处理此类问题?

基本上,对于第二种形式,我想要一个“删除”按钮,单击该按钮时,会调用控制器删除项目,删除项目,然后返回 Index() 视图。

【问题讨论】:

标签: c# html asp.net-mvc forms


【解决方案1】:

我认为改进您的设计将使您遇到的问题不再是问题。听起来您认为一切都可能必须通过您的 Index() 方法,但事实并非如此。将方法的名称重新设计为动作的行为通常是我命名方法的方式。

基本上,对于第二种形式,我希望有一个“删除”按钮,当单击该按钮时,调用控制器删除项目,删除项目,然后返回 Index() 视图。

因此,创建名为 Remove() 的方法并将其重定向到 Index()

public ActionResult Remove(int id)
{
  // do some work 

  this.RedirectToAction("Index");
}

我建议让您的方法名称代表他们正在做的事情。

public ActionResult Add(int regID, int jobID)
{
  // do some work

  this.RedirectToAction("Index");
}

注意:这也是用户界面的一个重要设计。当一个页面通常对服务器进行 POST,然后服务器返回 HTML,如果用户决定刷新页面,通常会显示一个弹出窗口,询问他们是否要重新提交数据。相反,前面的示例进行了服务器端重定向,它以 GET 形式启动第二个请求,并防止在刷新时出现弹出窗口。

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多