0

I'm trying to scrape Google search results in MVC with the help of Google search API. But then, there's an error in my view saying that search_list is NullReferenceException.

public void Search(string searchString)
    {
        const string apiKey = "AIzaSyDE5amOomu_BqZF9pWktULIb-ffPDJK0-k";
        const string searchEngineId = "003470263288780838160:ty47piyybua";
        string query = searchString;

        CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });

        CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
        listRequest.Cx = searchEngineId;
        Search search = listRequest.Execute();

        List<SearchList> search_list = new List<SearchList>();
        foreach (var item in search.Items)
        {

            var list = new SearchList();
            list.AdLink = item.Link;
            list.AdTitle = item.Title;
            list.AdDetails = item.Snippet;
            search_list.Add(list);
        }
    }

and my code in view

<div>
@if (Model.search_list.Count != 0)
{ 
    <ul class="clearfix">
        @foreach (var item in Model.search_list)
        {
            <li>@item.AdLink</li>
            <li>@item.AdTitle</li>
            <li>@item.AdDetails</li>
        }
    </ul>
    }
</div>

my controller

 public ActionResult Index(string SearchString)
    {
        if (!string.IsNullOrEmpty(SearchString))
        {
            var search = new GoogleSearch();
            search.Search(SearchString);
        }
            return View();
    }

When I debug it, my search_list is not null though. Can someone help me here?

Dean
  • 23
  • 7
  • Do you have a controller, which has an ActionResult for this view that uses your Search method from above? The Search method from above is intended to be used inside a controller's ActionResult, so that whatever search_list you generate can be passed on to the view with something like "return this.View(search_list);". If you say search_list is not empty, then may be you're passing it incorrectly. – Stoyan Berov Nov 30 '16 at 05:57
  • @StoyanBerov I added the code in my controller in the question. I am calling the method inside the ActionResult. Please check. I am new in MVC so I am not that familiar yet. – Dean Nov 30 '16 at 06:31
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Linda Lawton - DaImTo Nov 30 '16 at 08:18

0 Answers0