Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple forms in MVC3

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.

like image 668
Vivendi Avatar asked Jun 28 '26 10:06

Vivendi


2 Answers

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.

like image 71
Iridio Avatar answered Jun 30 '26 00:06

Iridio


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.

like image 23
Thabiso Mofokeng Avatar answered Jun 30 '26 01:06

Thabiso Mofokeng