usr4217
usr4217

Reputation: 440

How passing properly parameters value in HttpPost Action in ASP.NET MVC?

I am trying to submit the value of the submit button that was clicked to a controller method but the parameter in the method is not being bound to the value of the clicked button.

View

@using (Html.BeginForm())
{
    ....
    <input type="submit" name="test" value="TEST"  />
    <input type="submit" name="test" value="TEST22" />
}

Controller

[HttpPost]
public ActionResult Index(string action)
{
    // the value of action is null
    ....
    return View();
}

Upvotes: 1

Views: 426

Answers (1)

user3559349
user3559349

Reputation:

A form will submit the name/value pairs (based on the name and value attributes) of successful controls. In the case of an <input type="submit" ... />, it will be the value of the button that was clicked (values of other submit buttons will not be submitted).

In your case, you are giving the buttons a name="test" attribute which means the form will submit either test: TEST or test: TEST22 (depending on which button you clicked) so therefore the POST method must be

public ActionResult Index(string test)

alternatively, you could change each button to have name="action"

Upvotes: 1

Related Questions