ASP.NET MVC - What is the best way to build a search form that works properly with SEO and users without JS?

对着背影说爱祢 提交于 2020-01-05 06:28:07

问题


I'm working on building a search engine in my application, and because I don't want to have a Querystring in my URL, I'm currently using Javascript to submit the searchTerms for me.

Basically I am NOT using a "form", but rather just an input

<input id="searchBox" class="search" name="searchTerm" tabindex="1" onfocus=" this.className = 'search-alt'; if (this.value=='search...') this.value = ''" type="text" onkeypress="searchKeyPress(event,this.form)" maxlength="80" size="28" value="search...">

<script type="text/javascript">
    function searchKeyPress(e, form) {
        var key = e.keyCode || e.which;
        if (key == 13) {window.location.href = '<%: url.Content("~/search") %>/' + $('#searchBox').val();}}
</script>

The problem with this method is "two fold"

  1. If the user doesn't have Javascript, the form will not submit
  2. I'm not sure if a search engine will be able to use this search form either

So my question is

Can I use a Form element on my page that can submit " http://example.com/search/{searchTerms} " instead of " http://example.com/search/?q={searchTerms} " while NOT using Javascript?

I'm using ASP.NET MVC 2


回答1:


Ok, I think I've found my solution. Basically I am using RedirectToAction if there is a querystring item.

View

 <form action="/search/" id="searchForm" method="get">
    <input id="searchBox" class="search-gray" name="searchTerms" tabindex="1" onblur=" if (this.value==''){this.value = 'search...'; this.className = 'search-gray'}" onfocus=" this.className = ''; if (this.value=='search...') {this.value = ''}" type="text" maxlength="80" size="28" value="search...">
</form>

Controller

    Function Index(Optional ByVal searchTerms As String = "") As ActionResult

        If Not Request.QueryString("searchTerms") = "" Then
            Return RedirectToAction("Index", "Search", New With {.searchTerms = searchTerms})
        End If

        ViewData("searchTerms") = searchTerms
        Return View()
    End Function

No more javascript.



来源:https://stackoverflow.com/questions/3536171/asp-net-mvc-what-is-the-best-way-to-build-a-search-form-that-works-properly-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!