与ScriptManager.RegisterStartupScript一起使用时,为什么要删除脚本中的反斜杠

时间:2014-01-26 08:06:59

标签: c# javascript asp.net

我有这个C#代码,它为在某个目录中找到的每个文件生成1个启动脚本:

foreach (System.IO.FileInfo item in _imageAddress.GetFiles())
{
    db.insertXmlNode("SliderInformation", "SliderImageAddress", "..\\Uploades\\Img\\" + item.Name + ",", "Name", counter++.ToString());
    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", @"loadNewPic('..\Uploades\Img\'" + item.Name + ",');", true);
}

以下是Javascript代码:

function loadNewPic(picName) {
    $.ajax({
        type: "GET",
        url: "../Static/Css/xml/data.xml",
        dataType: "xml",
        success: function (xml) {
            console.log("NAME:   " + picName)
            $(xml).find('SliderInformation').each(function () {
                _name = $(this).find('SliderImageAddress:contains(' + picName + ')').text();
                console.log(_name);
            });

            var k = 0;
            for (var i = 0; i < listToAray(_name, ",").length; i++) {
                setTimeout(function () { 
                    $("#image-holder")
                        .append("<img src='" + listToAray(_name, ",")[k] + "' width='80' height='80' />")
                        .fadeIn('slow'); k++; 
                }, 300 * i);
            }
        }
    });
}

function listToAray(fullString, separator) {
    var fullArray = [];
    if (fullString !== undefined) {
        if (fullString.indexOf(separator) == -1) {
            fullAray.push(fullString);
        } else {
            fullArray = fullString.split(separator);
            fullArray.pop(-1)
        }
    }

    return fullArray;
}

即使我使用反斜杠生成我的脚本调用loadNewPic 我还没有反斜杠获取值 / strong>当我将picName输出到浏览器控制台时。

我得到了这个: ..UploadesImg'Hydrangeas.jpg

但我想要检索这个: ..\Uploades\Img\Hydrangeas.jpg

为什么反斜杠被移除?

2 个答案:

答案 0 :(得分:0)

当您编写包含字符串的脚本(服务器端)时,您需要使用HttpUtility.JavaScriptStringEncode

对该字符串进行编码

请尝试类似:

foreach (System.IO.FileInfo item in _imageAddress.GetFiles())
{
    ...
    var pathToImageEncoded = HttpUtility.JavaScriptStringEncode("..\Uploades\Img\" + item.Name);
    var scriptToLoadPic = string.Format("loadNewPic('{0}');", pathToImageEncoded);
    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", scriptToLoadPic, true);
}

答案 1 :(得分:-1)

因为它是字符串的字符串。 \是一个控制角色,您需要使用反斜杠\\来转义它。

(旁注:你的问题对于你所要求的东西来说有太多的复杂性 - 继续削减并减少它直到你得到最小的一块来证明这个问题。 - 这可能有助于你弄明白。 )

编辑:看下面的评论 - 你不清楚你在哪里看到问题,你的值也被用在javascript中的munged字符串中,它可能是正在进行插值的javascript。