How to pass parameter to MVC controller

Asked

Viewed 1,805 times

4

How to pass the text or content of a DropDownList to the Controller by pressing a button?

I tried using @model and I couldn’t. I tried adding the [HttpPost] in the Controller and using the type button submit and it didn’t even work.

Controller:

public ActionResult Pesquisar(string _ddl)
{
  string opcaoDdl = _ddl;
  return View();
}

Index:

 @Html.DropDownList("ddlListaUnidades", new SelectList(ViewBag.listaUnidades), new { @class = "dllListaUnidades" })

<div class="botoesfiltrodiv">

    <input class="filtro-buttons" type="button" value="Limpar" />
    <input class="filtro-buttons" type="button" value="Pesquisar" onclick="location.href='@Url.Action("Pesquisar", "UnidadeAtendimento")'" />

</div>

When I push the button, it even calls the controller, but I cannot pass the parameter.

1 answer

6


The role of Controller must bear the same name as tag generated in the case ddlListaUnidades:

[HttpPost()]
[ValidateAntiForgeryToken()]
public ActionResult Pesquisar(string ddlListaUnidades)
{    
    string opcaoDdl = ddlListaUnidades;    

    return View();
}

and in part <form> have to use like this:

@using (Html.BeginForm("Pesquisar","UnidadeAtendimento", FormMethod.Post)) 
{
    @Html.AntiForgeryToken()
    @Html.DropDownList("ddlListaUnidades", new SelectList(ViewBag.listaUnidades),
                   new { @class = "dllListaUnidades" })    
    <div class="botoesfiltrodiv">    
        <input class="filtro-buttons" type="button" value="Limpar" />
        <input class="filtro-buttons" type="submit" value="Pesquisar" />    
    </div>

}

References and Readings:

  • Thanks for the feedback, Virgilio, but I had already done this test before, and it still didn’t work. I just tested it again, and it still hasn’t worked.

  • @Evandrosilva I saw more problems and edited the answer, give a check please

  • I’ll try, although I’ve tried it this way, but I haven’t inserted @Html.Antiforgerytoken(), I’ll test it and I’ll get back to you. Thanks

  • 1

    Thank you very much, problem solved. Really was the issue the Antiforgerytoken

Browser other questions tagged

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