0

Let's say I have a page with 2 forms that both submit different data on the same page, one submits two ID's, and the other submits only 1 ID. They are both posting back to the same page (itself). Here is what the HTML would look like...

<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>

Now, to handle the first form in the controller I can do

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

However, if I try to handle the second form by adding

 [HttpPost]
 public ActionResult Index(int ID)
 {
 ....
 }

When I click the submit button, I will now get the error

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 

So, is it possible in the controller to overload the [HttpPost] method with different values to handle 2 different sets of form data, or is this not possible? Is there another solution I might not be grasping to handle this sort of issue?

Basically, for the second form I want to have a "Remove" button that when clicked, calls the controller to remove the item, removes the item, then returns the Index() view.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Clay Smith
  • 1,051
  • 14
  • 27

1 Answers1

3

I think an improvement in your design would make the problem you are having not an issue anymore. It sounds like you believe everything might have to go through your Index() method, which is not the case. Redesigning your method's name to the behavior of what the action is doing is typically how I name my methods.

Basically, for the second form I want to have a "Remove" button that when clicked, calls the controller to remove the item, removes the item, then returns the Index() view.

So create your method called Remove() and have it redirect to the Index()

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

  this.RedirectToAction("Index");
}

I would recommend making your method names represent what they are doing.

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

  this.RedirectToAction("Index");
}

Note: This is also an important design for the User Interface. When a page typically does a POST to the server, and then the server returns HTML, if the users decides to refresh the page , a popup will typically be presented asking them if they want to resubmit data. Instead the previous examples did a server side redirect, which starts a second request as a GET and prevents the popup from occurring on refresh.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150