Result-google-search-console-in-mvc-page

Add Google custom search in asp.net MVC website

Add Google custom search in asp.net MVC website

Hello folks, today we will discuss regarding how to add google custom search in asp.net MVC website!! It is very difficult to add full text search or provide whole website search functionality easily. To over come this problem we will see how can we add google custom search in asp.net MVC website. Same way you can also add google search in asp.net website or HMTL website as well.

Step-1:  Setup your google search engine.

To setup your google search engine first go to https://cse.google.com/cse/ -> New search engine -> add your site for which you want to do configuration and hit Create button as shown below image.

 

Google-Seach-console-configuration

 

Step-2: Copy code snippet

Go to Edit Search engine  -> Select your website name  -> Setup -> In Basic tag -> Press on “Get Code” -> Copy code snippet for your future use.

Google-Seach-console-Code-snippet

Step-3: Create new project of MVC in visual studio.

Refer my another post to create MVC project ASP.NET MVC step by step- Hello World!.

Step-4: Add below code in _Layout.cshtml

<div style="width:300px; text-align:right; margin-bottom:10px;">
    <input type="text" value="Search" style="width:200px;"
            id="q" name="q" onblur="if(this.value == '') this.value=this.defaultValue;"
            onfocus="if(this.value == this.defaultValue) this.value = '';"
            onkeypress="return SubmitOnEnter(this, event);" class="form-control" />
    <input type="button" value="Search" onclick="SiteSearch();" style="padding:4px; margin:0px;" class="form-control" />
</div>

<script type="text/javascript">
    function SubmitOnEnter(searchBox, event) {
        var keyCode;
        if (window.event) {
            keyCode = window.event.keyCode;
        }
        else if (event) {
            keyCode = event.which;
        }
        else {
            return true;
        }
        if (keyCode == 13) {
            // This is for Enter Key
            SiteSearch();
            return false;
        }
        else {
            return true;
        }
    }

    function SiteSearch() {
        document.location.href = "/GoogleSearch/SearchPosts?q=" +
            EncodeText(document.getElementById('q').value); // Here we should use url encode for the user input
    }

    function EncodeText(value) {
        var returnValue = "";
        var x = 0;
        var regex = /(^[a-zA-Z0-9_.]*)/
        while (x < value.toString().length) {
            var match = regex.exec(value.substr(x));
            if (match != null && match.length > 1 && match[1] != '') {
                returnValue += match[1];
                x += match[1].length;
            }
            else {
                if (value[x] == ' ') {
                    returnValue += '+';
                }
                else {
                    var charCode = value.charCodeAt(x);
                    var haxValue = charCode.toString(16);
                    returnValue += "%" + (haxValue.length < 2 ? '0' : '') + haxValue.toUpperCase();
                }
                x++;
            }
        }
        return returnValue;
    }
</script>

 

Step-5: Add new “GoogleSearchController” Controller and add below code snippet with Action named with “SearchPosts”.

using System.Web.Mvc;

namespace GoogleSearch.Controllers
{
    public class GoogleSearchController : Controller
    {
        // GET: /GoogleSearch/SearchPosts/q

        public ActionResult SearchPosts(string q)
        {
            return View();
        }
    }
}

 

Step-6: Add View for this controller and add below code snippet.

@{
    ViewBag.Title = "SearchPosts";
}

<h2>Search Posts</h2>


<script>
    (function () {
        var cx = '004190376073915964254:jgkqwbmrfpe';
        var gcse = document.createElement('script');
        gcse.type = 'text/javascript';
        gcse.async = true;
        gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
            '//www.google.com/cse/cse.js?cx=' + cx;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(gcse, s);
    })();
</script>
<gcse:searchresults-only></gcse:searchresults-only>

 

Step-7: Add routing to get proper search engine enabled URL by adding below code snippet in RouteConfig.cs as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace GoogleSearch
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "SearchMovie",
               url: "GoogleSearchController/{action}/{q}",
               defaults: new { controller = "GoogleSearchController", action = "SearchPosts", q = UrlParameter.Optional }
           );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 

Finally we will run our code and it will land on Index page of website as below:

Landing-page-for-Google-Search-MVC
Landing-page-for-Google-Search-MVC

And after searching with specific keyword we will be redirected to result page as show below:

Result-google-search-console-in-mvc-page
Result-google-search-console-in-mvc-page

 

 

Leave a Reply