Pass parameters to the Controller via @Html.Action

Asked

Viewed 4,895 times

2

I need to render one View into another, but this rendered View needs to receive and display data from the database, so I’m going to use @Html.Action for this, but I need to pass a parameter to the method in the controller to fetch the data in the database based on that parameter and to rederizate the View with the data. The problem is that the way I did the parameter is not passed, it is always null.

View:

    @Html.Action("ExibirCliente", "Cliente", new {idcliente = Model.ID})

Controller:

    [Authorize]
    public ActionResult ExibirCliente(int idcidade)
    {
        Cliente c = new Cliente();
         c = c.BuscarCliente(idcidade);
        return PartialView("~/Views/Shared/_ViewCLiente.cshtml", cep);
    }

2 answers

4

The parameter name in the View and Controller should be the same, so you are only receiving null. Just change your View to

@Html.Action("ExibirCliente", "Cliente", new {idcidade = Model.ID})

since your Controller expects to receive a parameter called idcidade.

3


The parameter passed to the anonymous object has to be exactly the same in the signature of Action. See that:

@Html.Action("ExibirCliente", "Cliente", new {idcliente = Model.ID})

The parameter is idcliente, while in the Action:

public ActionResult ExibirCliente(int idcidade)

Obviously the Model Binder will not make the correlation and the parameter will be null.

Now, if you modify to:

@Html.Action("ExibirCliente", "Cliente", new {idcidade = Model.ID})

Will work.

  • 1

    Thank you guys, I knew that the names had to be the same, but I passed the code step by step and did not see the name different from the variable.... What a blunder Thank you Rsrs, now obviating worked...

Browser other questions tagged

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