How to pass a string as a parameter in Action

Asked

Viewed 108 times

0

I need to pass as a parameter a string where it returns all items that have the same name. Here he is returning Null.

With Id it works perfectly.

[HttpGet, ActionName("Search")]
public async Task<IActionResult> Search([FromQuery] string hosts)
{
    if (hosts == null)
    {
        return NotFound();
    }
    return View(_context.Histories.Where(x => x.Host == hosts).ToList());
}

1 answer

2


You need to define where this value comes from.

In case of a GET request, it may come from the route:

[HttpGet("{hosts}"), ActionName("Search")]
public async Task<IActionResult> Search([FromRoute] string hosts)
{
    ...
}

In this case the call would be: http://url-base/Search/valor-hosts.

Or you can receive it via querystring

[HttpGet, ActionName("Search")]
public async Task<IActionResult> Search([FromQuery] string hosts)
{
    ...
}

The call would be: http://url-base/Search?hosts=valor-hosts.

It is also possible to receive a value of a header, but I doubt it’s useful now.


According to his comment, the same problem is in the assembly of view. Here’s an example of how to do.

@{
    var querystringValues = new Dictionary<string, string>
    {
        { "hosts", "teste-teste" }
    };
}

<a asp-controller="Histories" asp-action="Search"
   asp-all-route-data="querystringValues">Clique aqui</a>
  • Hello, he keeps returning Null, strange..

  • @Matheusls How are you calling the route?

  • <a Asp-controller="Histories" Asp-action="Search" Asp-route-id="@item. Host" >, that’s what I call in the View.

  • It makes no sense to use asp-route-id to send a querystring. Take a look in the documentation

  • @Matheusls Anyway, this is not a problem in the controller but in the view. You should have specified this in the question (along with the view code).

  • It worked, thanks for the help and sorry for the lack of attention =p

Show 1 more comment

Browser other questions tagged

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