问题描述:

I have searched high and low and cannot find an answer to this one, plenty of ajax and irrelevant links. Answers only in C# MVC please (no aspx files etc.)

I would like to use a form on one piece of cshtml to read in the query into the google cse and so I am using the google results only page option in CSE. The problem being is they do not specify how to get the results out to the javascript and having only briefly done js about 10 years ago I cannot figure out how to do this and need some help.

I would like to send my query to the search controller which then generates the page with the google results in it. The google javascript is listed in the layout page.

Header cshtml file with google search in it

<form class="navbar-form input-group-sm btn-group" gname="gsearch" role="search" method="post" action="@Url.Action("Index", "Search")">

<div class="navbar-form input-group-addon input-group-sm btn-group-sm" style="background-color:transparent">

<input class="form-control" name="q" size="20" style="vertical-align:bottom;margin:0px;padding:0px" maxlength="255" value="search site" onclick="value = '';" />

<button class="btn btn-default btn-sm" type="submit" style="margin:0px"><i class="glyphicon glyphicon-search" style="margin:0px;"></i></button>

</div>

</form>

Controller

public class SearchController : Controller

{

//

// GET: /Search/

[HttpPost]

public ActionResult Index(string q)

{

return View();

}

}

Search page .cshtml

<div class="gcse-searchresults" >

<gcse:searchresults-only linkTarget="_top" gname="gsearch"></gcse:searchresults-only>

Figured out what was going on:

In my declaration I should have used method="get" instead of method post and I should have declared [HttpGet] before the function in SearchController instead of [HttpPost], code works fine now.

网友答案:

In the controller the program needed [HttpGet] instead of [HttpPost] with no variable required (as the js handles it)

[HttpGet]
    public ActionResult Index()
    {
        return View();
    }

In the header.cshtml the first line of the form needed changing from method="post" to method = "get"

<form class="navbar-form  input-group-sm btn-group" gname="gsearch" role="search" method="get" action="@Url.Action("Index", "Search")">

Hope this helps anyone else with MVC & CSE integration.

相关阅读:
Top