简体   繁体   English

如何将 html 块从代码后面(C#)传递到 javascript function

[英]How to pass a html block from code behind(C#) to a javascript function

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:我目前正在写我的期末论文。我有一个小问题。我需要将一个 HTML 块传递给一个 javascript ZC1C425268E68385D1AB5074C17A94FI14Z 的字符串块。因为它将起作用。这是代码隐藏中的代码:

string htmlFlightDetailsJavaScript ;

In the string there are few div and tables which have class propeties.在字符串中,很少有具有 class 属性的 div 和表。 something like div class="bla"像 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:这是我的 javascript function:

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

Note that my javascript function is on the ~.aspx.请注意,我的 javascript function 在 ~.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?我试图传递没有在 div 中的类和在字符串中的表的字符串并且它正在工作。但是当我尝试通过类传递它时,它不起作用。有人可以帮助我吗?

Thank you very much非常感谢

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, eg div class='bla' .如果htmlFlightDetailsJavaScript中的类采用div class="bla"的形式,您可能必须转义字符串中的引号或使用单引号,例如div class='bla'

Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML.使用 RegisterClientScriptBlock() 方法并确保在 HTML 中转义引号。

"<div class=\"blah\">" "<div 类=\"废话\">"

This sounds like invalid Javascript is being generated .这听起来像无效的 Javascript 正在生成

This hypothesis can be verified with inspecting the actual Javascript transmitted and verifying the entire result, in context, for correctness.这个假设可以通过检查实际传输的 Javascript 并在上下文中验证整个结果的正确性来验证。

That is, imagine that this invalid Javascript was generated:也就是说,假设生成了这个无效的 Javascript:

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

To fix this, ensure the strings literals inserted into the Javascript are valid.要解决此问题,请确保插入 Javascript 的字符串文字有效。

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;-) (看看这个 output 并比较:插入的文字仍然有效 Javascript,即使在theInput中有引号或其他字符。作为额外的奖励, </script>也可以破坏代码;-)

This code is "free to use, modify, sell, whatever".这段代码是“免费使用、修改、出售等等”。 YMMV. 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.快乐编码。

I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself.如果您使用 ajax 调用和部分控件(用户控件)或自己编写内容,我想您可以更快地完成。

1) The user control will render your html data. 1) 用户控件将呈现您的 html 数据。 2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. 2) 后面的页面代码会接收到 ajax 调用并调用方法 thal 将呈现部分控制或写入。 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. 3) 该方法将写入 Response.Output stream 并结束响应 (Response.End()) 4) javascript 将处理响应并显示结果。

(using jQuery) (使用 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: You can use a Generic Handler if you wish to. PS:如果您愿意,可以使用通用处理程序。 Just add the url option to jQuery ajax method.只需将 url 选项添加到 jQuery ajax 方法即可。

Let me know if it helps.让我知道它是否有帮助。

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.我会退后一步检查整个 HTML 块是否真的如此动态,以至于需要将其作为参数传递到 function 中。

The easier way would be to have the HTML element emitted as part of the page, then augment that from your function.更简单的方法是将 HTML 元素作为页面的一部分发出,然后从 function 中增加它。 ie. 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.如果您的方案仍需要您将 HTML 作为参数传递,则需要HTML 在服务器端对整个字符串进行编码,然后在 JS 中进行Unencode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM