Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

Implement search from inside layout in asp.net core mvc

I'm creating my first web app using asp.net core mvc, so I'm stuck with implementing global search using textbox inside layout, I can't find where to implement the search after user press Enter, Is it implemented in controller or something else, and how to implement it...

question from:https://stackoverflow.com/questions/65861143/implement-search-from-inside-layout-in-asp-net-core-mvc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm stuck with implementing global search using textbox inside layout, I can't find where to implement the search after user press Enter

To implement the above requirement, you can refer to the following code snippet.

Adding form with input for searching functionality in _Layout.cshtml

<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
    <ul class="navbar-nav flex-grow-1">
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </li>
        <li class="nav-item">
            <form id="f_search" method="get" asp-action="Search">
                <div class="form-group">
                    <div class="input-group">
                        <input id="ipt_search" type="search" class="form-control" name="SearchTerm" />
                        <span class="input-group-btn">
                            <button class="btn btn-default">
                                Search
                            </button>
                        </span>
                    </div>
                </div>
            </form>
        </li>
    </ul>
</div>

JS code of checking keydown event and user input

<script>
    $(function () {
        $('#f_search input').keydown(function (e) {

            var searchTerm = $("#ipt_search").val();

            if (searchTerm == "" && event.keyCode === 13) {
                e.preventDefault();
                return false;
            }
        });
    })
</script>

Action method of Search

public IActionResult Search(string SearchTerm)
{
    //...
    //do query based on SearchTerm

    //code logic here
    //...

    return View();
}

Test Result

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...