简体   繁体   English

我如何根据URL中的参数填充我的搜索字段

[英]how i can populate my search fields based on the parameters inside the URL

I am working on an asp.net web application and i have the following code to build a search fields section, which build the URL parameters based on the users' input:- 我正在开发一个asp.net Web应用程序,我有以下代码来构建一个搜索字段部分,它根据用户的输入构建URL参数: -

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {  
        var count=1;
        var s="";

        var inputvalue = $("#journal").val();
        var inputvalue2 = $("#keywords").val();
        var inputvalue3 = $("#datepub").val();
        var inputvalue4 = $("#title").val();
        var inputvalue5 = $("#localcurrency").val();
        var inputvalue6 = $("#locations").val();
        var inputvalue7 = $("#dropdown1").val();
        var inputvalue8 = $("#dropdown2").val();

        if(inputvalue!=null && inputvalue!="")
        {
        s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
        count++;
        }
        if(inputvalue2!=null && inputvalue2!="")
        {
        s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
        count++;
        }
        if(inputvalue3!=null && inputvalue3!="")
        {
        s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
        count++;
        }
        if(inputvalue4!=null && inputvalue4!="")
        {
        s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
        count++;
        }
        if(inputvalue5!=null && inputvalue5!="")
        {
        s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
        count++;
        }
        if(inputvalue6!=null && inputvalue6!="")
        {
        s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
        count++;
        }
        if(inputvalue7!=null && inputvalue7!="")
        {
        s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
        count++;
        }
        if(inputvalue8!=null && inputvalue8!="")
        {
        s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
        count++;
        }
        window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);

    });
});
</script> 

       Journal <input type="text" id="journal"> 
       keywords <input type="text" id="keywords"> 




<select id="datepub">
<option value=""></option>
  <option value="1950">1950</option>
  <option value="2010">2010</option>
  <option value="2017">2017</option>
  <option value="audi">Audi</option>
</select>

title
<select id="title">
<option value=""></option>
  <option value="TestDoc">test doc</option>
  <option value="t">t</option>

</select>

localcurrency
<select id="localcurrency">
<option value=""></option>
  <option value="USD">USD</option>

</select>

locations
<select id="locations">
<option value=""></option>
  <option value="US">US</option>
  <option value="UK">UK</option>

</select>

dropdown1
<select id="dropdown1">
<option value=""></option>
  <option value="a">a</option>
  <option value="b">b</option>

</select>

dropdown2
<select id="dropdown2">
<option value=""></option>
  <option value="aa">aa</option>
  <option value="bb">bb</option>
  <option value="cc">cc</option>
  <option value="dd">dd</option>
</select>
       <button type="button" id="button">search</button>

Where when the user clicks on the search button, the user will be redirected to the /teamsites/Bib%20Test/Forms/search.aspx page with the filter parameters inside the url, which will show the related records according to the parameters being passed. 当用户点击搜索按钮时,用户将被重定向到/teamsites/Bib%20Test/Forms/search.aspx页面,其中包含url内的过滤器参数,将根据传递的参数显示相关记录。

now the filtering is working well.. but the problem i am facing is that after i redirect the user to this page /teamsites/Bib%20Test/Forms/search.aspx the filter fields values (such as the local currency, locations, title, etc..) will cleared out. 现在过滤效果很好..但我面临的问题是,在我将用户重定向到此页面/teamsites/Bib%20Test/Forms/search.aspx ,过滤字段值(例如本地货币,位置,标题)等等。)将清除。 so can i using JavaScript to assign the filer fields their original values ? 那么我可以使用JavaScript为文件管理器字段分配其原始值吗? i mean can i extract the fields' values from the URL and assign it to them ? 我的意思是我可以从URL中提取字段的值并将其分配给它们吗? so after the user is being redirected to the /teamsites/Bib%20Test/Forms/search.aspx they can still see the filtering fields populated with the filtering values they have entered? 所以在用户被重定向到/teamsites/Bib%20Test/Forms/search.aspx他们仍然可以看到填充了他们输入的过滤值的过滤字段?

You can accomplish this by doing the following: 您可以通过执行以下操作来完成此操作:

  • Parse the current page's query string to separate out its query parameters 解析当前页面的查询字符串以分离其查询参数
  • Process those to match up filter field names with their values 处理那些匹配过滤器字段名称及其值的过程
  • Use $('#' + fieldName).val(value) to set the field values in the page 使用$('#' + fieldName).val(value)设置页面中的字段值

Below, as a demonstration, I'm passing in a hardcoded query string '?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b' into the populateSearchFields() function. 下面,作为演示,我将一个硬编码的查询字符串'?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b'传入populateSearchFields()函数。 In practice, you would use the three functions here, unmodified, but instead of that hardcoded value, pass in window.location.search . 在实践中,您将使用未修改的三个函数,但不是硬编码值,而是传入window.location.search

 // input: '?a=b&b=c&e=f' // output: { a: 'b', b: 'c', e: 'f' } function buildParameterMap(queryString) { // ignore the ? at the beginning and split the query string into // pieces separated by & var pairs = queryString.replace(/^\\?/, '').split('&'); var map = {}; pairs.forEach(function(pair) { // further split each piece to the left and right of the = // ignore pairs that are empty strings if (pair) { var sides = pair.split('='); map[sides[0]] = decodeURIComponent(sides[1]); } }); return map; } // input: { FilterField0: 'Name', FilterValue0: 'Fred', // FilterField1: 'age', FilterValue1: '30' } // output: { name: 'Fred', age: '30' } function buildFilterFieldMap(parameterMap) { var maxFieldCount = 15; var map = {}; for (var i = 0; i < maxFieldCount; i += 1) { var filterFieldName = parameterMap['FilterField' + i]; if (filterFieldName) { map[filterFieldName.toLowerCase()] = parameterMap['FilterValue' + i]; } } return map; } function populateSearchFields(queryString) { // build a map from URL query string parameter -> value var parameterMap = buildParameterMap(queryString); // build a map from search field name -> value var filterFieldMap = buildFilterFieldMap(parameterMap); Object.keys(filterFieldMap).forEach(function(field) { $('#' + field).val(filterFieldMap[field]); }); } populateSearchFields('?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> Journal <input type="text" id="journal"> keywords <input type="text" id="keywords"> <select id="datepub"> <option value=""></option> <option value="1950">1950</option> <option value="2010">2010</option> <option value="2017">2017</option> <option value="audi">Audi</option> </select> title <select id="title"> <option value=""></option> <option value="TestDoc">test doc</option> <option value="t">t</option> </select> localcurrency <select id="localcurrency"> <option value=""></option> <option value="USD">USD</option> </select> locations <select id="locations"> <option value=""></option> <option value="US">US</option> <option value="UK">UK</option> </select> dropdown1 <select id="dropdown1"> <option value=""></option> <option value="a">a</option> <option value="b">b</option> </select> dropdown2 <select id="dropdown2"> <option value=""></option> <option value="aa">aa</option> <option value="bb">bb</option> <option value="cc">cc</option> <option value="dd">dd</option> </select> <button type="button" id="button">search</button> 

You want to send get request from one page to another. 您希望将get请求从一个页面发送到另一个页面。 Do something like this: 做这样的事情:
Part I: send search request in the query string. 第一部分:在查询字符串中发送搜索请求。

$(document).ready(function(){

    $('#button').click(function(e) {  
        var count=1; //out of use
        var s = []; //""; //empty array, not empty string

        var inputvalue = $("#journal").val();
        var inputvalue2 = $("#keywords").val();
        var inputvalue3 = $("#datepub").val();
        var inputvalue4 = $("#title").val();
        var inputvalue5 = $("#localcurrency").val();
        var inputvalue6 = $("#locations").val();
        var inputvalue7 = $("#dropdown1").val();
        var inputvalue8 = $("#dropdown2").val();

        if(inputvalue) // !=null && inputvalue!="") //it is redundant. null and empty string are **falsey**
        {
            s.push('journal='+inputvalue);
            //or if you wish to keep your existing format (not recommended because it would produce problems on the search page)
            //s.push("FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue);
            //count++;
        }
        if(inputvalue2) //!=null && inputvalue2!="")
        {
           s.push('keywords='+inputvalue2);
        //for existing format see previous comment
        //s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
        //count++;
        }
        /*
        //same for other vars
        if(inputvalue3!=null && inputvalue3!="")
        {
        s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
        count++;
        }
        if(inputvalue4!=null && inputvalue4!="")
        {
        s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
        count++;
        }
        if(inputvalue5!=null && inputvalue5!="")
        {
        s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
        count++;
        }
        if(inputvalue6!=null && inputvalue6!="")
        {
        s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
        count++;
        }
        if(inputvalue7!=null && inputvalue7!="")
        {
        s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
        count++;
        }
        if(inputvalue8!=null && inputvalue8!="")
        {
        s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
        count++;
        }
        */
        window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s.join('&')); //Use the array here

    });
});

Part II: Restore values in the search fields. 第二部分:恢复搜索字段中的值。

$(document).ready(function(){
    var query = window.location.search.slice(1); //get ?.... less **?**
    var terms = query.split('&'); //get pairs like key=value
    for(var i = 0, term; term = terms[i]; ++i){ //loop the search terms
       var detail = term.split('='); //journal=some
       $('#'+detail[0]).val(detail[1]); //set the value provided fields have the same **id**s
    }
});

Update based on comments 根据评论更新

It is all about ASP.NET . 这完全是关于ASP.NET .aspx page prepends server control ID s with parent ID s like parId$controlId . .aspx页面使用父IDparId$controlId服务器控件ID ,如parId$controlId To avoid it and make the client script work set ClientIDMode="Static" attribute to the controls in search.aspx . 为了避免它并使客户端脚本工作,将ClientIDMode="Static"属性设置为search.aspx的控件。

<asp:TextBox ID="keywords" runat="server" ClientIDMode="Static"></asp:TextBox>

Update 2 更新2

The OP is about ASP.NET . OP是关于ASP.NET的 Generally speaking the result can be achieved without any client-side code. 一般来说, 无需任何客户端代码即可实现结果。

Part I 第一部分

<form method="GET" action="/search.aspx">
   <input type="text" name="keywords" />
   <select name="localcurrency">
     <option value="USD">US Dollar</option>
     <option value="EUR">Euro</option>
   </select>
   <!--other fields -->
   <input type="submit" value="Search" />
</form>

Part II 第二部分

<%-- search.aspx --%>
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["keywords"] != null)
                this.keywords.Text = Request.QueryString["keywords"];
            if (!string.IsNullOrEmpty(Request.QueryString["localcurrency"]))
                localcurrency.SelectedValue = Request.QueryString["localcurrency"];
            //other request query strings
            // DoSearch();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="keywords" runat="server"></asp:TextBox>
            <asp:DropDownList runat="server" ID="localcurrency">
                <asp:ListItem Value="USD">US Dollar</asp:ListItem>
                <asp:ListItem Value="EUR">Euro</asp:ListItem>
            </asp:DropDownList>
        </div>
    </form>
</body>
</html>

Use this if you are not concerned about Internet Explorer or Edge. 如果您不关心Internet Explorer或Edge,请使用此选项。

When your page has loaded, you can read the search params with the help of URL API . 页面加载后,您可以在URL API的帮助下阅读搜索参数。 Below is the code to get you started. 以下是帮助您入门的代码。

Note that this solution depends on being the form param's ID to be equal to the lower cased search param's name. 请注意,此解决方案取决于表单param的ID等于下层的搜索参数名称。

 $(document).ready(() => { // Change the value to window.location.href for working with browser's URL instead const href = "http://yourhost.com?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b"; // Initializes the URL object with current location const url = new URL(href); // This array will contain all the FilterFields const keys = []; for (let entry of url.searchParams) { if (entry[0].startsWith("FilterField")) { keys.push(entry[0]); } } keys.forEach(field => { // Extract the index of FilterField const idx = field[field.length - 1]; // Get the value of FilterField (this gives us the ID of the form field) const formField = url.searchParams.get(field).toLowerCase(); // Set the value of form field using .val() $("#" + formField).val(url.searchParams.get('FilterValue' + idx)); }); // Rest of the code here }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Journal <input type="text" id="journal"> keywords <input type="text" id="keywords"> <select id="datepub"> <option value=""></option> <option value="1950">1950</option> <option value="2010">2010</option> <option value="2017">2017</option> <option value="audi">Audi</option> </select> title <select id="title"> <option value=""></option> <option value="TestDoc">test doc</option> <option value="t">t</option> </select> localcurrency <select id="localcurrency"> <option value=""></option> <option value="USD">USD</option> </select> locations <select id="locations"> <option value=""></option> <option value="US">US</option> <option value="UK">UK</option> </select> dropdown1 <select id="dropdown1"> <option value=""></option> <option value="a">a</option> <option value="b">b</option> </select> dropdown2 <select id="dropdown2"> <option value=""></option> <option value="aa">aa</option> <option value="bb">bb</option> <option value="cc">cc</option> <option value="dd">dd</option> </select> <button type="button" id="button">search</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用URL参数填充空白值而不是“ undefined”的字段? - How do I populate fields with a blank value instead of “undefined” using URL Parameters? 如何基于网络中的单个字段进行多次搜索 - How can I do a multiple search based on single fields in my web 如何根据页面URL在数据库中填充页面上的表单字段? - How do I populate form fields on a page from a database based on the page url? 如何根据查询参数搜索猫鼬? - How can I search in mongoose according to my query parameters? 如何使用JavaScript使用URL参数填充嵌入式网站表单? - How can I populate an embedded website form with URL parameters using Javascript? 如何加密和解密查询我在 URL 中的查询参数? - How can I encrypt and decrypt query my query parameters in a URL? 如何从URL填充textarea? - How can I populate a textarea from a URL? 我根据获取的数据创建输入字段,但是如何仅将输入字段作为目标值 - I create input fields based on my fetched data, but how can I only target the input fields with a value 为什么我不能用用户的URL填充数组? - Why can't I populate my array with the URL from the user? 我可以将搜索框值作为参数传递给函数吗? - Can I pass my search box values as parameters in my function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM