SomeoneNew
SomeoneNew

Reputation: 91

How to call a method from controller when a button from form is pressed?

The main problem is that a method from controller is not called when i press a button. I have this in my Index view for MyController :

@using (Html.BeginForm())
{
@* .... *@
<form action="DoSomethingAction" method="post">
    <input type="text" id="IdString" name="IdString" placeholder="Enter id"/>
    <input id="Submit1" name="Submit1" type="submit" value="DoSomething1" />
    <input id="Submit2" name="Submit2" type="submit" value="DoSomething2" />
</form>
@* ..... *@
}

In MyController I have DoSomethingAction method. I want to call this method and be able to see IdString when I press a button: DoSomething1 or DoSomething2. This is DoSomethingAction method from controller:

 public ActionResult DoSomethingAction()
    {
        string id= Request.Form["IdString"];
        //string button=...

        // ...
    }

When I put a breakpoint for DoSomethingAction method, I observed that it's never called. I tried to put [Httppost] attribute for this method, but it didn't solve my problem.

What am I doing wrong? After that, how can I see in DoSomethingAction method which button was pressed?

Upvotes: 0

Views: 106

Answers (2)

Serlok
Serlok

Reputation: 462

Either use html.BeginForm or type="Submit". Next thing to keep in mind, html.BeginForm is a post method, so if u want to use it, give an attribute over Action and if u don't state what view action should return, he will assume that view is of the same name as action, in ur case DoSomethingAction, that's why u get server error. Either make that view or state in return View() which view u want to return (Index or some other).

Upvotes: 0

Anirudha Gupta
Anirudha Gupta

Reputation: 9279

a HTML form can not nest a HTML form. Please read https://www.w3.org/TR/html5/forms.html#the-form-element

If you need multiple form you can define them as siblings.

Upvotes: 1

Related Questions