将.html字符串传递给javascript作为参数,采用.Net Web表单

时间:2017-04-27 05:04:48

标签: javascript html .net

我有一个包含html的html文件:

<html>
    <body>
        <div class="infoLabel">*Your order has been placed in production queue</div><br />
        <div class="infoLabel">*The order confirmation will be delivered to you shortly</div> 
    </body>
</html>

在.net C#代码后面我编写以下代码将html转换为字符串并传递给Javascript:

string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Templates/SiteNotifications/SavedQuote.html");
string htmlBody = File.ReadAllText(path);
ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList" + Guid.NewGuid(),"displayViewDetails(" + htmlBody + ");", true);

我发现htmlBody包含正确转义的字符串。脚本是:

function displayViewDetails(currentOrder) {
    var w = window.open('_blank', "NewWindow", "width=" + width + ", height=" + height);
    w.document.open();
    w.document.write(currentOrder);
    w.document.close();
}

然而,在调试时我发现Javascript解析html时出错。我不知道如何正确传递用于解析Javascript的html。我发现现有的帖子似乎无法解决我的问题。有人可以帮忙吗?

使用IE调试时的错误快照: enter image description here

1 个答案:

答案 0 :(得分:1)

出现此问题是因为在解析文件时,会将新行字符添加到字符串:\r\n。那些不是有效的HTML标记。解决方案是在将新行字符传递给javascript函数之前删除它们。你可以这样做:

string htmlBody = File.ReadAllText(path).Replace(Environment.NewLine, " ");

注意Environment.NewLine是给定平台的新行字符,来自.NET文档:

  

包含&#34; \ r \ n&#34;的字符串对于非Unix平台,或包含&#34; \ n&#34;的字符串对于Unix平台。