MVC: parameter in URL is not being passed to controller

1

I'm running the Action below, but the "CategoryObject" parameter is not being passed to the Controller. I'm working with asp.net core 2.0.

public async Task<IActionResult> Buscar(string ArtigoOuCategoria)
{
    ...
}

The Action call is below:

 <div class="card mb-4">
        <div class="card-body">
            <h4 class="card-title">Categorias</h4>
            @foreach (var item in Model.Categorias)
            {
                <a class="btn btn-light btn-sm mb-1" asp-controller="Artigo" asp-action="Buscar/@item.Descricao">@item.Descricao</a>
            }
        </div>
    </div>

The Action call was also made as follows:

<a href="Artigo/Buscar/@item.Descricao">@item.Descricao</a>

Includes the route instructions in the project startup.cs file:

  routes.MapRoute(
          name: "buscar",
          template: "Artigo/Buscar/{ArtigoOuCategoria?}",
          defaults: new { controller = "Artigo", action = "Buscar" });
    
asked by anonymous 08.07.2018 / 19:16

3 answers

3

Gleison,

Solution 1

You need to put in the [FromQuery] method thus:

public async Task<IActionResult> Buscar([FromQuery] string ArtigoOuCategoria)

{     ... }

But to work you need to call it like this:

<a href="Artigo/[email protected]">@item.Descricao</a>

Solution 2

Declare your method thus

[HttpPost("Buscar/{ArtigoOuCategoria}")] 
public async Task<IActionResult> Buscar(string ArtigoOuCategoria)
    
08.07.2018 / 20:23
0

Friend, first, to call this action, it must have the HttpGet attribute to access that way with the href of a button.

Second: To pass this parameter to the action, use the button as follows:

<a class="btn btn-light btn-sm mb-1" asp-controller="Artigo" asp-action="Buscar" asp-route-artigooucategoria="@item.Descricao">@item.Descricao</a>

Your action should be in this pattern:

[HttpGet]    
public async Task<IActionResult> Buscar([FromRoute] string ArtigoOuCategoria)
{
    ...
}

Source: Working with forms

    
09.07.2018 / 01:32
0

Make sure your default route is set:

routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");

and change your link to this, using the asp-route- attribute:

<a asp-controller="Artigo"
   asp-action="Buscar"
   asp-route-ArtigoOuCategoria="@item.Descricao">Edit</a>

See that ArtigoOuCategoria after asp-route must be the same as the parameter name of your, action, so it's coming null for you.

Tip : Put a break point in your Search method, and in Google Crhome, press crtr + swift + j , and go to the Network tab, and then click on the button to call the action Search, you will see that the call of your action will appear, clicking on it, you can go to the Headers sub-tab, and check what is happening to your action. p>     

09.07.2018 / 20:36