Problem passing path string to web service function via jQuery.ajax

I need to make a call to an asp.net web service function through jQuery and pass the path of the asp.net application to it. The way I am trying to do it (the code is on the asp.net page, like the aspx file):

    var d = "{'str':'<%=System.DateTime.Now.ToString() %>', 'applicationPath':'<%=GetApplicationPath() %>'}";

    $.ajax({ type: "POST",
        url: "http://localhost/testwebsite/TestWebService.asmx/Test",
        data: d,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        },
        success: function (msg) {

        }
    });

      

This is what the GetApplicationPath method looks like:

protected string GetApplicationPath() 
{
    return HttpUtility.HtmlEncode(Request.PhysicalApplicationPath);
}

      

And here is the header of the web service function I'm trying to call:

public void Test(string str, string applicationPath) 

      

The function call works well, but the applicationPath parameter is not being passed correctly. When I debug it, I see the backslashes are removed, the function gets "C: ProjectsSamplesmytestwebsite" instead of "C: \ Projects \ Samples \ mytestwebsite \".

How can I overcome this?

+2


a source to share


2 answers


OK give this shot, I tried it (works on my machine).

protected string GetApplicationPath()
{
    return Request.PhysicalApplicationPath.Replace(@"\", @"\\");
}

      



Then for javascript. Here I am using the JSON JavaScript library to ease the transition.

// construct object literal to be JSON-stringified
var d = {
    str: "<%=System.DateTime.Now.ToString() %>",
    applicationPath: "<%=GetApplicationPath() %>"
};

$.ajax({ type: "POST",
    url: "http://localhost/testwebsite/TestWebService.asmx/Test",
    data: JSON.stringify(d),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    error: function (xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
    },
    success: function (msg) {

    }
});

      

+3


a source


Backslashes must be escaped in JavaScript. Try replacing "\" with double backslashes "\\" (minus the space):

protected string GetApplicationPath()  
{ 
    return Request.PhysicalApplicationPath.Replace("\", "\\"); 
}

      



I don't think you need the HTMLEncode part.

+1


a source







All Articles