I have a webpage with a form, which looks kinda like this:
@using (Html.BeginForm("MyAction", "Controller", FormMethod.Post))
{
// html input fields here
// ...
// [SUBMIT]
}
When a user presses on the submit button, then the following function is called:
public ActionResult MyAction ( string id )
{
// default action
}
[HttpPost]
public ActionResult MyAction ( MyModel model )
{
// called when a form is submitted
}
Now my problem is, is that i have to add another form. But how can i tell which form was submitted? Because both will now end up in the second (HttpPost) method...
What would be a good way to separate both form actions? Please note that when a form is submitted, that i must stay on the same page. I can't redirect myself to another page/controller.
If I understand your question correctly you will have a page with two forms in it. As a first approach I will post each form to a different action of the same controller.
The first
@using (Html.BeginForm("MyAction", "Controller", FormMethod.Post))
The second
@using (Html.BeginForm("MyAction2", "Controller", FormMethod.Post))
and then, a little refactoring on your two actions to follow the DRY principle.
If instead you need both form to post to the same action, then I will put a hidden input to let me know wich one was called.
If you have multiple forms on one page/view and would like to post to different actions add the name html attribute to the beginform method:
@using (Html.BeginForm("action1", "contollerName", new { @name = "form1" }))
{
...add view code
}
@using (Html.BeginForm("action2", "contollerName", new { @name = "form2" }))
{
...add view code
}
Having a different name for each form will allow MVC to easily determine which action to post to rather than relying on different form collection values to figure this out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With