Martin Mazza Dawson Martin Mazza Dawson - 5 months ago 3x
Javascript Question

Remove 'X-Requested-With' from query string url during ajax request

The problem I am having is that

keeps being appended to my url because it is apart of the query string. Is there a way that I can stop it from becoming a query string and doing
without doing a 'hack'?

@using (Ajax.BeginForm("Search", "Filter", new { Area = "Music" }, new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "body-wrapper", OnSuccess = "updateHistory" }, new { @id = "search-form" }))
<i class="fa fa-search"></i>
<input type="search" placeholder="Search" id="search" name="searchString" />

public ActionResult Search(string searchString)
//do stuff
return PartialView();

On the partial view page I then get the path and query:

@Html.HiddenFor(x => Request.Url.PathAndQuery)

The value of
is :

And then update the url using History.js:

function pushState(target) {
manualStateChange = false;
History.pushState(null, null, $("#Request_Url_PathAndQuery").val());

enter image description here


What I gone with is this, although it's a hack and not really desirable, so if anyone finds a better way please say. It removes the query string parameter from the url, it works because xhr is always appended at the end.

function pushState(target) {
    //Remove the queryString parameter of xhr that gets appened in 117 of ajax-unobtrusive.js
    var index = target.indexOf("?X-Requested-With");
    if (index === -1) 
        index = target.indexOf("&X-Requested-With");

    target = target.replace(target.substring(index), "");

    manualStateChange = false;
    History.pushState(null, $("input#Title").val(), target);

Edit. New Answer Based on Mike comment:

@using (Html.BeginForm("Index", "Search", new { area = "Media" }, FormMethod.Get, new { @id = "search", data_url = Url.Action("SetSearchTags", "Search", new { Area = "Media" }) }))
    <i class="fa fa-search"></i>
    <input type="search" placeholder="Search" id="search" name="searchString" />

    <div id="filter" name="filter">

        @foreach (var item in SearchContext.SearchFilters)
            <div id="filter-@item">
                @Html.DisplayFor(x => item)

$("form#search").submit(function (event) {

    var $form = $(this);
    var searchString = $form.find("input[type='search']").val();
    var url = $form.attr("action");
    var method = $form.attr("method");

        url: url,
        data: { searchString: searchString },
        method: method,
        success: function (data) {

function updateHistory(useQuery) {
    var path = (useQuery === true) ? $("#Request_Url_PathAndQuery").val() : $("#Request_Url_AbsolutePath").val();


Basically, wherever I need query string parameters I'll just have to manually do it in jquery and not use helpers.