I’m doing a project for the College, and I’m having a hard time understanding how to create a button and call an Actionresult in the Controller...
If we’re talking about a <input>
of the kind submit
(which is a kind of button), the right way is to create a <form>
for him. In ASP.NET MVC using Razor, it works as follows:
@using (Html.BeginForm("MinhaAction", "MeuController", FormMethod.Get))
{
<input type="submit" value="Ir para Action"
name="botao1" id="botao1" />
}
Or using the tag <button>
:
@using (Html.BeginForm("MinhaAction", "MeuController", FormMethod.Get))
{
<button type="submit" name="botao1" id="botao1">Ir para Action</button>
}
To work, your Controller need to have:
[HttpGet]
public ActionResult MinhAction()
{
...
}
..., and wanted to know if the action needs to be in the corresponding controller of the respective Model.
Not necessarily. A Model is not necessarily linked to a Controller. A Controller can work with 0, 1 or N Models.
To better understand, this would be a view with 2 buttons, 2 actions in the controller and make a button call action1 and the other call action2
It can be done like this:
@using (Html.BeginForm("MinhaAction1", "MeuController", FormMethod.Get))
{
<button type="submit" name="botao1" id="botao1">Ir para Action 1</button>
}
@using (Html.BeginForm("MinhaAction2", "MeuController", FormMethod.Get))
{
<button type="submit" name="botao2" id="botao2">Ir para Action 2</button>
}
Controller:
[HttpGet]
public ActionResult MinhAction1()
{
...
}
[HttpGet]
public ActionResult MinhAction2()
{
...
}
In the case of@using (Html.Beginform("Minhaaction", "Meucontroller", Formmethod.Get)) { <input type="Submit" value="Go to Action" name="botao1" id="botao1" /> }' how would I pass my object to the action? In case my project needs to have a buy button for each item, and the button is displayed by foreach and each item has the ID...
– Fabio Souza
I suggest you ask a new question, now talking about this new need. It is a new answer, complementary to this.
– Leonel Sanches da Silva