如何将 html 块从代码隐藏 (C#) 传递到 javascript 函数

发布于 2024-11-03 12:55:10 字数 695 浏览 1 评论 0原文

我目前正在写我的期末论文。我有一个小问题。我需要将一个 HTML 块(它是一个字符串块)传递给 javascript 函数。我必须从代​​码后面执行此操作。我已经尝试了很多次,但似乎没有这是代码隐藏中的代码:

string htmlFlightDetailsJavaScript ;

在字符串中,很少有具有类属性的 div 和表。类似于 div class="bla"

ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("fill("+htmlFlightDetailsJavaScript+");");
cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true);

这是我的 javascript 函数:

function fill(b) 
{
   alert(b);
}

请注意,我的 javascript 函数位于 ~.aspx 上。

我试图传递没有类的字符串,这些类位于 div 和字符串中的表中,并且它正在工作。但是当我尝试通过类传递它时,它不起作用。任何人都可以帮助我吗?

非常感谢

I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind:

string htmlFlightDetailsJavaScript ;

In the string there are few div and tables which have class propeties. something like div class="bla"

ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("fill("+htmlFlightDetailsJavaScript+");");
cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true);

Here is my javascript function:

function fill(b) 
{
   alert(b);
}

Note that my javascript function is on the ~.aspx.

I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me?

Thank you very much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

想你的星星会说话 2024-11-10 12:55:10

这听起来像是正在生成无效的 Javascript

这个假设可以通过检查实际传输的 JavaScript 并在上下文中验证整个结果的正确性来验证。

也就是说,假设生成了这个无效的 Javascript:

alert("<div class="I just broke JS" ...>")

要解决此问题,请确保插入 Javascript 中的字符串文字有效。

例如,上面的内容可能会编写为(使用以下代码):

RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput))

。 ..并且它不会中断,因为字符串之前已被转义。 (看一下这个输出并进行比较:插入的文字仍然是有效的 Javascript,即使在 theInput 中包含引号或其他字符。作为一个额外的好处,< /code> 来破解代码;-)

该代码是“免费使用、修改、出售等”。 YMMV。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace sbcjc.sei
{
        public class JsEncoder
        {
            static Regex EncodeLiteralRegex;

            // Format a bunch of literals.
            public static string Format (string format, params object[] items)
            {
                return string.Format(format,
                    items.Select(item => EncodeString("" + item)).ToArray());
            }

            // Given a string, return a string suitable for safe
            // use within a Javascript literal inside a <script> block.
            // This approach errs on the side of "ugly" escaping.
            public static string EncodeString (string value)
            {
                if (EncodeLiteralRegex == null) {
                    // initial accept "space to ~" in ASCII then reject quotes 
                    // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues)
                    // "/" is not allowed because it requires an escape in JSON
                    var accepted = Enumerable.Range(32, 127 - 32)
                        .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' });
                    // pattern matches everything but accepted
                    EncodeLiteralRegex = new Regex("[^" +
                        string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray())
                        + "]");
                }
                return EncodeLiteralRegex.Replace(value ?? "", (match) =>
                {
                    var ch = (int)match.Value[0]; // only matches a character at a time
                    return ch <= 127
                        ? @"\x" + ch.ToString("x2") // not JSON
                        : @"\u" + ch.ToString("x4");
                });
            }
        }
}

快乐编码。

This sounds like invalid Javascript is being generated.

This hypothesis can be verified with inspecting the actual Javascript transmitted and verifying the entire result, in context, for correctness.

That is, imagine that this invalid Javascript was generated:

alert("<div class="I just broke JS" ...>")

To fix this, ensure the strings literals inserted into the Javascript are valid.

For instance, the above might be written (using the following code) as:

RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput))

...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the theInput. As an added bonus, </script> to break the code either ;-)

This code is "free to use, modify, sell, whatever". YMMV.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace sbcjc.sei
{
        public class JsEncoder
        {
            static Regex EncodeLiteralRegex;

            // Format a bunch of literals.
            public static string Format (string format, params object[] items)
            {
                return string.Format(format,
                    items.Select(item => EncodeString("" + item)).ToArray());
            }

            // Given a string, return a string suitable for safe
            // use within a Javascript literal inside a <script> block.
            // This approach errs on the side of "ugly" escaping.
            public static string EncodeString (string value)
            {
                if (EncodeLiteralRegex == null) {
                    // initial accept "space to ~" in ASCII then reject quotes 
                    // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues)
                    // "/" is not allowed because it requires an escape in JSON
                    var accepted = Enumerable.Range(32, 127 - 32)
                        .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' });
                    // pattern matches everything but accepted
                    EncodeLiteralRegex = new Regex("[^" +
                        string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray())
                        + "]");
                }
                return EncodeLiteralRegex.Replace(value ?? "", (match) =>
                {
                    var ch = (int)match.Value[0]; // only matches a character at a time
                    return ch <= 127
                        ? @"\x" + ch.ToString("x2") // not JSON
                        : @"\u" + ch.ToString("x4");
                });
            }
        }
}

Happy coding.

染年凉城似染瑾 2024-11-10 12:55:10

如果 htmlFlightDetailsJavaScript 中的类采用 div class="bla" 形式,您可能必须转义字符串中的引号或使用单引号,例如 div class ='bla'

If the classes in htmlFlightDetailsJavaScript are in the form div class="bla" you likely have to escape the quotes in the string or use single quotes, e.g. div class='bla'.

太傻旳人生 2024-11-10 12:55:10

使用 RegisterClientScriptBlock() 方法并确保转义 HTML 中的引号。

"

"

Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML.

"<div class=\"blah\">"

裸钻 2024-11-10 12:55:10

我会退后一步,检查整个 HTML 块是否真的如此动态,以至于需要将其作为参数传递到函数中。

更简单的方法是将 HTML 元素作为页面的一部分发出,然后从您的函数中对其进行扩充。 IE。显示或隐藏它。

如果您的方案仍然需要您将 HTML 作为参数传递,则需要 在服务器端对整个字符串进行 HTML 编码,然后在 JS 中取消编码

I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter.

The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it.

If your scenario still requires you to pass the HTML as a parameter, you'll need to HTML encode the entire string on the server side, and then Unencode in JS.

沐歌 2024-11-10 12:55:10

我想如果您使用 ajax 调用和部分控件(用户控件)或自己编写内容,您可以更快地完成。

1) 用户控件将呈现您的 html 数据。
2)后面的页面代码将接收ajax调用并调用方法thal将渲染部分控件或写入。
3) 该方法将写入 Response.Output 流并结束 Response (Response.End())
4) javascript 将处理响应并显示结果。

(使用 jQuery)

// main.js

jQuery.ajax({
    type: 'POST',
    data: { isajax: true, ajaxcall: 'MyMethod' },
    dataType: 'html',
    success: function (data, textStatus, jqXHR) {
        alert(data);
    }
});

// CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.HttpMethod == "POST" && Request["isajax"] == "true")
    {
        this.AjaxCall(Request);
    }
}

private void AjaxCall(HttpRequest request)
{
    switch (request["ajaxcall"])
    {
        case "MyMethod": this.MyMethod(request); break;
        default: break;
    }
}

private void MyMethod(HttpRequest request)
{
    Response.ContentType = "text/html";

    Response.Write("YOUR CONTENT GOES HERE.");
    // Or, render a User Control

    Response.End();
}

PS:如果您愿意,可以使用通用处理程序。只需将 url 选项添加到 jQuery ajax 方法即可。

如果有帮助请告诉我。

I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself.

1) The user control will render your html data.
2) The page code behind will receive the ajax call and call the method thal will render the partial control or write.
3) The method will write on Response.Output stream and end the Response (Response.End())
4) The javascript will handle the response and show the result.

(using jQuery)

// main.js

jQuery.ajax({
    type: 'POST',
    data: { isajax: true, ajaxcall: 'MyMethod' },
    dataType: 'html',
    success: function (data, textStatus, jqXHR) {
        alert(data);
    }
});

// CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.HttpMethod == "POST" && Request["isajax"] == "true")
    {
        this.AjaxCall(Request);
    }
}

private void AjaxCall(HttpRequest request)
{
    switch (request["ajaxcall"])
    {
        case "MyMethod": this.MyMethod(request); break;
        default: break;
    }
}

private void MyMethod(HttpRequest request)
{
    Response.ContentType = "text/html";

    Response.Write("YOUR CONTENT GOES HERE.");
    // Or, render a User Control

    Response.End();
}

P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method.

Let me know if it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文