Call action with button click passing parameter

0

I will have 3 buttons, each with a different id, how do I pass this id to the action of my controller when it is clicked?

public IActionResult Index(int id)
    {
        var lista = _listaService.sites(id);
        return View(lista);
    }
    
asked by anonymous 21.09.2018 / 02:28

1 answer

2

You can use Razor Helpers to create links to actions by passing the specific id of each button. In your view you can do:

<a href="@Url.Action("Index", new { id = 1 })" class="btn btn-primary">ID = 1</a>
<a href="@Url.Action("Index", new { id = 2 })" class="btn btn-primary">ID = 2</a>
<a href="@Url.Action("Index", new { id = 3 })" class="btn btn-primary">ID = 3</a>

or:

@Html.ActionLink("ID = 1", "Index", new { id = 1 }, new { @class = "btn btn-primary" })
@Html.ActionLink("ID = 2", "Index", new { id = 2 }, new { @class = "btn btn-primary" })
@Html.ActionLink("ID = 3", "Index", new { id = 3 }, new { @class = "btn btn-primary" })

Note that I'm using anchors in HTML by passing the Bootstrap class btn btn-primary so that the link is rendered as a button instead of a link. This way you will not need to create three forms with a button each or use jQuery binding in the onclick event of the button.

EDIT: If you need the id not to appear in the url, use Html.BeginForm for each button by assigning name and value as shown below:

@using (Html.BeginForm())
    {
        <button type="submit" class="btn btn-primary" value="1" name="id">ID = 1</button>
    }        
<br />
@using (Html.BeginForm())
{
    <button type="submit" class="btn btn-primary" value="2" name="id">ID = 2</button>
}
<br />
@using (Html.BeginForm())
{
    <button type="submit" class="btn btn-primary" value="3" name="id">ID = 3</button>
}
<br />
@if (Model != 0)
{
    <p>Olá o ID agora é @Model.ToString()</p>
}

In Controller do so:

public class TesteController : Controller
{
    public ActionResult Index()
    {
        int id = 0;
        if (Request.Form["id"] != null)
            id = Convert.ToInt32(Request.Form["id"]);

        //faça o que precisar fazer com a id

        return View(id);
    }
}
    
21.09.2018 / 02:57