Passing variable from ASP.net to JavaScript

后端 未结 7 1903
清歌不尽
清歌不尽 2020-11-29 05:15

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

7条回答
  •  迷失自我
    2020-11-29 05:56

    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
    {
        /// 
        /// Empty string for Java Script context
        /// 
        private const string JavaScriptEmptyString = "''";
    
    
        /// 
        /// Initializes character Html encoding array
        /// 
        private static readonly char[][] SafeListCodes = InitializeSafeList();
    
    
    
        /// 
        /// Encodes input strings for use in JavaScript.
        /// 
        /// String to be encoded.
        /// value indicating whether or not to emit quotes. true = emit quote. false = no quote.
        /// 
        /// Encoded string for use in JavaScript and does not return the output with en quotes.
        /// 
        /// 
        /// This function encodes all but known safe characters.  Characters are encoded using \xSINGLE_BYTE_HEX and \uDOUBLE_BYTE_HEX notation.
        /// 
        /// Safe characters include:
        /// 
        /// a-zLower case alphabet
        /// A-ZUpper case alphabet
        /// 0-9Numbers
        /// ,Comma
        /// .Period
        /// -Dash
        /// _Underscore
        ///  Space
        ///  Other International character ranges
        /// 
        /// 
        /// Example inputs and encoded outputs:
        /// 
        /// alert('XSS Attack!');'alert\x28\x27XSS Attack\x21\x27\x29\x3b'
        /// user@contoso.com'user\x40contoso.com'
        /// Anti-Cross Site Scripting Library'Anti-Cross Site Scripting Library'
        /// 
        /// 
        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);
        }
    
    
    
    
        /// 
        /// Initializes the safe list.
        /// 
        /// A two dimensional character array containing characters and their encoded values.
        [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;
        }
    }
    }
    

提交回复
热议问题