Read QueryString value from URL using jQuery

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Hi,

How can i convert  my url from http://localhost:344605 Details?name=jo to http://localhost:34405/Details/jo

 my jquery query string to pass data  is

$("#btnsubmit").click(function () {
    var Textdata = $('#txtdata').val();
    var url = "Details?name=" + encodeURIComponent(Textdata);
    window.location.href = url;
});

and global.asax is

void Application_Start(object sender, EventArgs e)
{

    RegisterRoutes(RouteTable.Routes);
}
public void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("Details", "Details{name}", "~/Details.aspx");
}

in Details.aspx.... cannot read query string value with the below code now(after adding Details.aspx to global.asax)

function getdealsearch() {
    var name = window.location.search.split('=')[1] == undefined ? '' : window.location.search.split('=')[1];
    $.ajax({
        type: "POST",
        url: "/WebService.asmx/Getbyname",

        data: '{Name:"' + name + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

Any code to read jquery query string and convert my url from http://localhost:34405/Details?name=jo to http://localhost:34405/Details/jo

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi jovceka,

Refer below code.

Global.asax

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e) 
    {
        RegisterRoutes(RouteTable.Routes);
    }
    
    static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("query2", "query2/{name}", "~/query2.aspx");
        routes.MapPageRoute("querystring3", "querystring3", "~/querystring3.aspx");
    }
</script>

HTML

querystring1.aspx

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script type="text/javascript">
    $(function () {
        var name1 = $('#txtName').val();
        $("#btnQueryString").bind("click", function () {
            var url = "query2/" + encodeURIComponent(name1);
            window.location.href = url;
        });
    });
</script>
<input type="text" id="txtName" name="Name" value="sam" />
<input type="button" id="btnQueryString" value="Send" />

query2.aspx

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script type="text/javascript">
    $(function () {
        $("#label1").html(window.location.toString().split('query2/')[1]);
        $("a").click(function (e) {
            e.preventDefault();
            var url = "querystring3";
            window.location.href = window.location.href.split('query2')[0] + url;
        });
    });
</script>
<a href="javascript:;">click</a>
<br />
<span id="label1"></span>

querystring3.aspx

<div>querystring3 page</div>

Screenshot