I'm doing a project for College, and I'm having a hard time understanding how to create a button and call an ActionResult on Controller ...
If we are talking about a <input>
of type submit
(which is a type of button ), the correct way is to create a <form>
for it. 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 by using the <button>
tag:
@using (Html.BeginForm("MinhaAction", "MeuController", FormMethod.Get))
{
<button type="submit" name="botao1" id="botao1">Ir para Action</button>
}
In order to work, your Controller needs to have:
[HttpGet]
public ActionResult MinhAction()
{
...
}
..., and wanted to know if the action must be in the corresponding controller of the respective Model.
Not necessarily. A Model is not necessarily bound to a Controller . A Controller can work with 0, 1 or N Models .
To understand better, it would be like this, a view with 2 buttons, 2 actions in the controler 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()
{
...
}