将变量从 ASP.net 传递给 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10540217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:46:54  来源:igfitidea点击:

Passing variable from ASP.net to JavaScript

javascriptasp.net

提问by user1363918

How to pass a variable from asp.net to JavaScript?

如何将变量从 asp.net 传递给 JavaScript?

回答by Habib

Create a property in your code behind

在后面的代码中创建一个属性

protected string MyProperty { get { return "your value"; } }

then in javascript

然后在javascript中

var myValue = "<%= MyProperty %>";

回答by RedFilter

There are a number of ways:

有多种方式:

1 - Write it out in your JavaScript with <%= myVariable %>
2 - Set a cookie server-side and then retrieve the cookie client side
3 - Set a hidden form input to your value
4 - Redirect to your page with the value as a querystring parameter, and then parse the params using JavaScript
5 - Build all your JavaScript server-side, save to a variable, and then write out the variable client-side.
6 - Retrieve the value with an AJAX request

1 - 使用 JavaScript 将其写出<%= myVariable %>
2 - 设置 cookie 服务器端,然后检索 cookie 客户端
3 - 将隐藏表单输入设置为您的值
4 - 将该值作为查询字符串参数重定向到您的页面,然后使用 JavaScript
5解析参数- 在服务器端构建所有 JavaScript,保存到变量,然后在客户端写出变量。
6 - 使用 AJAX 请求检索值

回答by Josh Mein

You can use an ASP.Net HiddenField. You just set its value on the server and retrieve it via javascript when you need it.

您可以使用 ASP.Net HiddenField。您只需在服务器上设置它的值,并在需要时通过 javascript 检索它。

Serverside

服务器端

hdf_Test.Value = "yourValue";

HTML

HTML

<asp:HiddenField runat="server" ID="hdf_Test" />

Javascript

Javascript

document.getElementById('hdf_Test').value

回答by Nikolai Borisik

  1. Use javascript tag

    <script>
        var var1 = @var1;  
        var var2 = @var2;  
    </script>
    
  2. Use hidden field

    <input type="hidden" value="@var1" id="h_var1"/>  
    <input type="hidden" value="@var2" id="h_var2" />`
    
  1. 使用 javascript 标签

    <script>
        var var1 = @var1;  
        var var2 = @var2;  
    </script>
    
  2. 使用隐藏字段

    <input type="hidden" value="@var1" id="h_var1"/>  
    <input type="hidden" value="@var2" id="h_var2" />`
    

in js

在js中

$(function()
{
    var var1 = $("#h_var1").val();
    var var2 = $("#h_var2").val();
}

3.Retrieve data via ajax using json

3.使用json通过ajax检索数据

var var1;
var var2;
    $.get(url,function(result)
    {
        var1 = result.var1; var2 = result.var2;
     }

@var syntax depend of your view engine. It maybe <%= Var1 %>

@var 语法取决于您的视图引擎。也许 <%= Var1 %>

回答by John Rodriguez

You can use this in your code behind:

您可以在后面的代码中使用它:

public string json;

公共字符串json;

you need to give it a value

你需要给它一个值

In your JavaScript you can enter:

在您的 JavaScript 中,您可以输入:

<script>
    var myVar = <%=json%>;
</script>

回答by X.Otano

If you want to get the string variable equivalent in your code side, this is code:

如果你想在你的代码端获得等效的字符串变量,这是代码:

Example:

例子:

string jsString= JsEncoder.JavaScriptEncode("This is an example of C# string to be converted to javascript string",true));

Class Code:

班级代码:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace stackoverlofw.JavascriptEncoder
{
public class JsEncoder
{
    /// <summary>
    /// Empty string for Java Script context
    /// </summary>
    private const string JavaScriptEmptyString = "''";


    /// <summary>
    /// Initializes character Html encoding array
    /// </summary>
    private static readonly char[][] SafeListCodes = InitializeSafeList();



    /// <summary>
    /// Encodes input strings for use in JavaScript.
    /// </summary>
    /// <param name="input">String to be encoded.</param>
    /// <param name="emitQuotes">value indicating whether or not to emit quotes. true = emit quote. false = no quote.</param>
    /// <returns>
    /// Encoded string for use in JavaScript and does not return the output with en quotes.
    /// </returns>
    /// <remarks>
    /// This function encodes all but known safe characters.  Characters are encoded using \xSINGLE_BYTE_HEX and \uDOUBLE_BYTE_HEX notation.
    /// <newpara/>
    /// Safe characters include:
    /// <list type="table">
    /// <item><term>a-z</term><description>Lower case alphabet</description></item>
    /// <item><term>A-Z</term><description>Upper case alphabet</description></item>
    /// <item><term>0-9</term><description>Numbers</description></item>
    /// <item><term>,</term><description>Comma</description></item>
    /// <item><term>.</term><description>Period</description></item>
    /// <item><term>-</term><description>Dash</description></item>
    /// <item><term>_</term><description>Underscore</description></item>
    /// <item><term> </term><description>Space</description></item>
    /// <item><term> </term><description>Other International character ranges</description></item>
    /// </list>
    /// <newpara/>
    /// Example inputs and encoded outputs:
    /// <list type="table">
    /// <item><term>alert('XSS Attack!');</term><description>'alert\x28\x27XSS Attack\x21\x27\x29\x3b'</description></item>
    /// <item><term>[email protected]</term><description>'user\x40contoso.com'</description></item>
    /// <item><term>Anti-Cross Site Scripting Library</term><description>'Anti-Cross Site Scripting Library'</description></item>
    /// </list>
    /// </remarks>
    public static string JavaScriptEncode(string input, bool emitQuotes)
    {
        // Input validation: empty or null string condition
        if (string.IsNullOrEmpty(input))
        {
            return emitQuotes ? JavaScriptEmptyString : string.Empty;
        }

        // Use a new char array.
        int outputLength = 0;
        int inputLength = input.Length;
        char[] returnMe = new char[inputLength * 8]; // worst case length scenario

        // First step is to start the encoding with an apostrophe if flag is true.
        if (emitQuotes)
        {
            returnMe[outputLength++] = '\'';
        }

        for (int i = 0; i < inputLength; i++)
        {
            int currentCharacterAsInteger = input[i];
            char currentCharacter = input[i];
            if (SafeListCodes[currentCharacterAsInteger] != null || currentCharacterAsInteger == 92 || (currentCharacterAsInteger >= 123 && currentCharacterAsInteger <= 127))
            {
                // character needs to be encoded
                if (currentCharacterAsInteger >= 127)
                {
                    returnMe[outputLength++] = '\';
                    returnMe[outputLength++] = 'u';
                    string hex = ((int)currentCharacter).ToString("x", CultureInfo.InvariantCulture).PadLeft(4, '0');
                    returnMe[outputLength++] = hex[0];
                    returnMe[outputLength++] = hex[1];
                    returnMe[outputLength++] = hex[2];
                    returnMe[outputLength++] = hex[3];
                }
                else
                {
                    returnMe[outputLength++] = '\';
                    returnMe[outputLength++] = 'x';
                    string hex = ((int)currentCharacter).ToString("x", CultureInfo.InvariantCulture).PadLeft(2, '0');
                    returnMe[outputLength++] = hex[0];
                    returnMe[outputLength++] = hex[1];
                }
            }
            else
            {
                // character does not need encoding
                returnMe[outputLength++] = input[i];
            }
        }

        // Last step is to end the encoding with an apostrophe if flag is true.
        if (emitQuotes)
        {
            returnMe[outputLength++] = '\'';
        }

        return new string(returnMe, 0, outputLength);
    }




    /// <summary>
    /// Initializes the safe list.
    /// </summary>
    /// <returns>A two dimensional character array containing characters and their encoded values.</returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This is necessary complexity.")]
    private static char[][] InitializeSafeList()
    {
        char[][] allCharacters = new char[65536][];
        for (int i = 0; i < allCharacters.Length; i++)
        {
            if (
                (i >= 97 && i <= 122) ||        // a-z
                (i >= 65 && i <= 90) ||         // A-Z
                (i >= 48 && i <= 57) ||         // 0-9
                i == 32 ||                      // space
                i == 46 ||                      // .
                i == 44 ||                      // ,
                i == 45 ||                      // -
                i == 95 ||                      // _
                (i >= 256 && i <= 591) ||       // Latin,Extended-A,Latin Extended-B        
                (i >= 880 && i <= 2047) ||      // Greek and Coptic,Cyrillic,Cyrillic Supplement,Armenian,Hebrew,Arabic,Syriac,Arabic,Supplement,Thaana,NKo
                (i >= 2304 && i <= 6319) ||     // Devanagari,Bengali,Gurmukhi,Gujarati,Oriya,Tamil,Telugu,Kannada,Malayalam,Sinhala,Thai,Lao,Tibetan,Myanmar,eorgian,Hangul Jamo,Ethiopic,Ethiopic Supplement,Cherokee,Unified Canadian Aboriginal Syllabics,Ogham,Runic,Tagalog,Hanunoo,Buhid,Tagbanwa,Khmer,Mongolian   
                (i >= 6400 && i <= 6687) ||     // Limbu, Tai Le, New Tai Lue, Khmer, Symbols, Buginese
                (i >= 6912 && i <= 7039) ||     // Balinese         
                (i >= 7680 && i <= 8191) ||     // Latin Extended Additional, Greek Extended        
                (i >= 11264 && i <= 11743) ||   // Glagolitic, Latin Extended-C, Coptic, Georgian Supplement, Tifinagh, Ethiopic Extended    
                (i >= 12352 && i <= 12591) ||   // Hiragana, Katakana, Bopomofo       
                (i >= 12688 && i <= 12735) ||   // Kanbun, Bopomofo Extended        
                (i >= 12784 && i <= 12799) ||   // Katakana, Phonetic Extensions         
                (i >= 19968 && i <= 40899) ||   // Mixed japanese/chinese/korean
                (i >= 40960 && i <= 42191) ||   // Yi Syllables, Yi Radicals        
                (i >= 42784 && i <= 43055) ||   // Latin Extended-D, Syloti, Nagri        
                (i >= 43072 && i <= 43135) ||   // Phags-pa         
                (i >= 44032 && i <= 55215) /* Hangul Syllables */)
            {
                allCharacters[i] = null;
            }
            else
            {
                string integerStringValue = i.ToString(CultureInfo.InvariantCulture);
                int integerStringLength = integerStringValue.Length;
                char[] thisChar = new char[integerStringLength];
                for (int j = 0; j < integerStringLength; j++)
                {
                    thisChar[j] = integerStringValue[j];
                }

                allCharacters[i] = thisChar;
            }
        }

        return allCharacters;
    }
}
}

回答by Ray Cheng

In HTML:

在 HTML 中:

<script type="text/javascript">
  alert(<%=Greetings()%>);
</script>

In code behind:

在后面的代码中:

protected string Greetings()
{
    return Microsoft.Security.Application.AntiXss.JavaScriptEncode("Hello World!");
}

AntiXss Library

AntiXss 库