【问题标题】:Google CSE in MVC4, trouble using a formMVC4 中的 Google CSE,使用表单时遇到问题
【发布时间】:2015-02-06 05:00:45
【问题描述】:

我搜索了高低,找不到这个答案,大量的 ajax 和不相关的链接。请仅在 C# MVC 中回答(无 aspx 文件等)

我想在一块 cshtml 上使用一个表单将查询读入 google cse,因此我在 CSE 中使用 google results only page 选项。问题是他们没有指定如何将结果输出到 javascript,并且大约 10 年前只做过短暂的 js,我无法弄清楚如何做到这一点,需要一些帮助。

我想将我的查询发送到搜索控制器,然后它会生成包含谷歌结果的页面。 google javascript 列在布局页面中。

包含 google 搜索的标题 cshtml 文件

<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>

控制器

public class SearchController : Controller
{

    //
    // GET: /Search/
    [HttpPost]
    public ActionResult Index(string q)
    {
        return View();
    }
}

搜索页面.cshtml

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

弄清楚发生了什么: 在我的声明中,我应该使用 method="get" 而不是方法 post,并且我应该在 SearchController 中的函数之前声明 [HttpGet] 而不是 [HttpPost],现在代码可以正常工作了。

【问题讨论】:

  • 刚刚发现我应该使用 HttpGet 而不是 HttpPost 调用

标签: c# forms asp.net-mvc-4 post google-custom-search


【解决方案1】:

在控制器中,程序需要 [HttpGet] 而不是 [HttpPost] 而不需要变量(由 js 处理)

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

在 header.cshtml 中,表单的第一行需要从 method="post" 更改为 method="get"

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

希望这可以帮助其他任何人进行 MVC 和 CSE 集成。

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多