Embed Google search API in Asp.net MVC

Google Search API introduction

Google provide facility to embed search results in our website. you can show search results to your visitors inside your website as compare to redirecting google search engine. Google Search API can be called using JavaScript. you are also able to show specific search results like only videos search results etc.

objectives

In this article we will learn how we can call Google API in Asp.net MVC.

GET Started

Create a new asp.net mvc project and Add a new controller name it GoogleAPIController. Add a index Action result and add its corresponding view.

GoogleAPIController Code

public ActionResult Index()
        {
            return View();
        }
        

index View Code

<pre class='prettyprint'>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<div class="col-lg-12">
    <div class="col-lg-6">
        <input type="search" id="SearchInput" class="form-control" placeholder="Enter Key words" />
        <br />
        <input type="submit" value="Search" class="btn-success" />
    </div>
    <div class="col-lg-6">
        <div id="searchResults">

        </div>
    </div>
</div>    
<script>
    google.load('search', '1');
    $(".btn-success").click(function () {
        ShowSerach();
    });

    
    function ShowSerach() {
        // Create a search control
        var searchControl = new google.search.SearchControl();
		//Add search type here
        searchControl.addSearcher(new google.search.VideoSearch());
		searchControl.addSearcher(new google.search.WebSearch());
      searchControl.addSearcher(new google.search.VideoSearch());
      searchControl.addSearcher(new google.search.BlogSearch());
      searchControl.addSearcher(new google.search.NewsSearch());
      searchControl.addSearcher(new google.search.ImageSearch());
      searchControl.addSearcher(new google.search.BookSearch());
      searchControl.addSearcher(new google.search.PatentSearch());
        searchControl.draw(document.getElementById("searchResults"));
        var GetString = $("#SearchInput").val();
        searchControl.execute(GetString);
    }
  
</script>

<style>
    .gsc-search-box{
        display:none;
    }
</style>

you can change search type by removing non-required search from //Add search type here section.

Result