How to update URL route after completing a search query in Asp.net core MVC?

Viewed 50

I am trying to update my URL route after a search action within my controller is completed using Asp.net core MVC.

Once I find the specific database object, I return the obj model into a View, but once the view is displayed with the correct Model information, the URL route/address does not change.

It remains as https://localhost:7236/Ingredient/Search
It should be more like: https://localhost:7236/Ingredient/Search?q{ingredient-name}/{id}

I am learning C# / .Net and trying to understand how things work. Pardon my lack of proper syntax/grammar when trying to describe my process.

Search Form Page

    <form asp-controller="Ingredient" asp-action="Search">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
            </div>
            <input class="search-input form-control" name="search" placeholder="Ingredient..." />
        </div>
        <hr />
        <div class="btn-group">
            <button type="submit" class="btn btn-primary">Search</button>
            <a asp-controller="Ingredient" asp-action="List" class="btn btn-outline-primary">View List</a>
        </div>
    </form>

Search Form Action in Controller

            // SEARCH --> HOMEPAGE
        // Search by title and return details page of the ingredient if correct
        public IActionResult Search(string search, Ingredient obj)
        {
            var getResult = from ingredient in _db.ingredients where ingredient.Name == search select ingredient;
            if(getResult.Count() > 0)
            {
                var result = getResult.FirstOrDefault();
                obj = result;
                return View("Info", obj);
            }
            else
            {
                return NotFound();
            }
            
        }
1 Answers

You can try to use

<input type="submit" class="btn btn-primary" value="Search"/>

to replace

<button type="submit" class="btn btn-primary">Search</button>

And since you only have a input named search in the form,the url will be like

https://localhost:7236/Ingredient/Search?search={...}

result:

enter image description here

Related