search bar in mvc


Index.cshtml  CODE
    <input type="text" id="prodId" size="7" />
    <button class="btn btn-info my-2 my-sm-0" caption="search" id="search-now"> Search</button>
    <div id="search-results"> </div>
put that on your page want your search bar to display.
the div id search results are where you want your search results to display.

In your views folder, create a Search Folder .
add item Razor View named _SearchRestults.cshtml (this is a partial) CODE
    @model LegoListViewModel
    <div class="row">
    @foreach (var lego in Model.Legos)
    {
            <div class="col-md-4">
            <figure><a href=" @lego.URL " target="_blank"><img src=" @lego.Images " />                                < /a><figcaption>  @lego.Description </figcaption> </figure>
            </div>
    }
            </div>

that takes items based on the mappings of the columns within the database in example url is a link which I wrap in html to make a link. I make this link an image link with the lego.Images.

Also In the same Search Folder create a Find.cshtml. CODE

@model LegoListViewModel
@{
    ViewData["Title"] = "Brickstructions";
}

@*<div class="jumbotron" style="float:left;padding-left:5px; width: 74%">
    <h3> built by Aaron Lilly</h3>
</div>*@
</div>
<div class="row">

    @foreach (var lego in Model.Legos)
    {
        <div class="col-md-4">
        <figure><a href=" @lego.URL " target="_blank"><img src=" @lego.Images " />                                 < /a><figcaption>  @lego.Description </figcaption> </figure>
        </div>
    }
       </div>

that is very similar so the partial in terms of code.

within your site.js file CODE
$(document).ready(function () {
    $('#search-now').click(function () {
        var SEARCHY = $('#prodId').val();
        $.ajax({
            type: 'POST',
            dataType: "html",
            data: { "search": SEARCHY },
            url: '/Search/Find',
            success: function (result) {
                $('#search-results').html(result);
            }
            });
    });
});

this grabs the results form the search bar then basically runs it through the Search Controller and the Find Action (method) then that does a(ajax) post with html as results which then is displayed based on where I put my search-results div.
   

Comments

Popular posts from this blog

Ruby arrays intermediate

Ruby Strings

Ruby Enumerable Modules