Call action with button click by passing parameter

Asked

Viewed 1,829 times

0

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

public IActionResult Index(int id)
    {
        var lista = _listaService.sites(id);
        return View(lista);
    }

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 am using HTML anchors passing the Bootstrap class btn btn-primary so that the link is rendered as a button instead of a link. This way you won’t need to create three Forms with one button each or use jQuery linking 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 assigning the name and the value as an example 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);
    }
}
  • I look for a way without using route, so that I just call the action and pass the id, but without appearing anything in the url

  • create a form for each button with Post method, so the id will not appear in the url, if I’m not mistaken another way to do this would be to put the [Httppost] annotation in the Action Index in your Controller

  • What I use to specify the id in the form?

  • I believe I have already managed to resolve rs, but I edited my reply according to your comment. Oh and forget what I said about using the [Httppost], I was really wrong.

  • I’ll check here later but I think I can do with one form, just add the event onclick= and assign to "submit();" on the button tag, so the three buttons stay in one form only.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.