locked
Calling C# Variables In An Aspx Page Generates Javascript Error RRS feed

  • Question

  • User1349647816 posted

    I am calling a few c# variables in an aspx page which brings through the variable values, the problem is correctly terminating the variables as I am getting a javascript error.

    var ccListJsonFront = <%= ccListJson %>
    var depListJsonFront = <%= depListJson %>
    var catListJsonFront = <%= catListJson %>
    
    /* I have also tried the above lines using a semicolon at the end to terminate the string but that doesn't make a difference eg.
    var ccListJsonFront = <%= ccListJson %>;
    var depListJsonFront = <%= depListJson %>;
    var catListJsonFront = <%= catListJson %>;  */
    
    var ccSelectArray = []; // line becomes underlined and breaks the application with the error message ccSelectArray is not defined
    var depSelectArray = [];
    var catSelectArray = [];

    How do I get this to work correctly?

    Tuesday, September 8, 2020 8:25 AM

All replies

  • User475983607 posted

    I am calling a few c# variables in an aspx page which brings through the variable values, the problem is correctly terminating the variables as I am getting a javascript error.

    var ccListJsonFront = <%= ccListJson %>
    var depListJsonFront = <%= depListJson %>
    var catListJsonFront = <%= catListJson %>
    
    /* I have also tried the above lines using a semicolon at the end to terminate the string but that doesn't make a difference eg.
    var ccListJsonFront = <%= ccListJson %>;
    var depListJsonFront = <%= depListJson %>;
    var catListJsonFront = <%= catListJson %>;  */
    
    var ccSelectArray = []; // line becomes underlined and breaks the application with the error message ccSelectArray is not defined
    var depSelectArray = [];
    var catSelectArray = [];

    How do I get this to work correctly?

    When asking for support on the forum always provide enough code to reproduce the issue without forcing the community to guess.  This means taking the time to write test code.  This does two things.  It forces you to focus on the problem.  Often this is all you need to find the bug in your design without needing to post on the forum.  If you still need support the test code allows community members to easily run the code and understand the intent without having to guess.

    Below is a basic example of rendering JavaScript from server side code using code blocks in an ASP.NET Web Forms application.

    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Deployment.Internal;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo.JSDemos
    {
        public class CcList
        {
            public int Value { get; set; }
            public string Text { get; set; }
        }
    
        public partial class Default : System.Web.UI.Page
        {
            public List<CcList> ccListJson { get; set; }
            public NameValueCollection depListJson { get; set; }
            public List<string> catListJson { get; set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    PopulateLists();
                }
            }
    
            private void PopulateLists()
            {
                ccListJson = new List<CcList>()
                {
                    new CcList()
                    {
                        Text = "Hello",
                        Value = 1
                    },
                    new CcList()
                    {
                        Text = "World",
                        Value = 2
                    }
                };
    
                depListJson = new NameValueCollection(2);
                depListJson.Add("Foo", "1");
                depListJson.Add("Bar", "2");
    
                catListJson = new List<string>() { "Red", "Yellow", "Blue" };
            }
    
        }
    }
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormsDemo.JSDemos.Default" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    
    
        <script>
            var ccListJsonFront = <%= System.Web.Helpers.Json.Encode(ccListJson) %>;
            var depListJsonFront = <%= System.Web.Helpers.Json.Encode(depListJson) %>;
            var catListJsonFront = <%= System.Web.Helpers.Json.Encode(catListJson) %>;
    
            console.log(ccListJsonFront);
            console.log(depListJsonFront);
            console.log(catListJsonFront);
        </script>
    </asp:Content>
    

    Tuesday, September 8, 2020 12:12 PM
  • User1349647816 posted

    mgebhard you're an all star, the code I have given you is enough to understand the problem and suggest a solution. In order for me to hit this wall of a bug I already have the written code. We cannot post all the code as it may be code in an application that we don't want publicly available. This really is a petty issue, if I had just posted the question you would have said post some code, now that I post code it isn't good or definitive enough AND at the end of it all you posted basically the same code that I posted in my question, where is the sense in that, honestly now.

    Too often this pettiness just erodes what this forum is trying to achieve, you are an all star you have sufficient information to understand and suggest a solution to the problem please don't make unnecessary issues where there need not be one. 

    Tuesday, September 8, 2020 12:46 PM
  • User475983607 posted

    ShatterStar

    mgebhard you're an all star, the code I have given you is enough to understand the problem and suggest a solution. In order for me to hit this wall of a bug I already have the written code. We cannot post all the code as it may be code in an application that we don't want publicly available. This really is a petty issue, if I had just posted the question you would have said post some code, now that I post code it isn't good or definitive enough AND at the end of it all you posted basically the same code that I posted in my question, where is the sense in that, honestly now.

    Too often this pettiness just erodes what this forum is trying to achieve, you are an all star you have sufficient information to understand and suggest a solution to the problem please don't make unnecessary issues where there need not be one. 

    I provided a clear and open solution as well as a recommendation to make you a better programming and considerate community member.   

    Your sample code is missing the actual type being serialized and how the variable is populated in the code behind.  Without this information it is very difficult to understand where the holes are in your understanding then provide an accurate solution.  That is why I shared three different types in the sample code; custom class, .NET framework type, and List<string>. 

    Please take the time to run and review the code sample.  If the demo code does not work for you then explain the expected results and actual results.  

    One type I missed is a basic string which needs quotes.

    public string stringExample { get; set; }
        <script>
            var stringEx = '<%= Server.HtmlEncode(stringExample)%>';
            console.log(stringEx);
        </script>

    Use HtmlDecode if you want to render markup and you trust the content.

    var stringEx = '<%= Server.HtmlDecode(stringExample)%>';

    Tuesday, September 8, 2020 12:58 PM
  • User475983607 posted

    If you are trying to set a C# variable from JavaScript, well, that's not possible.  You have to send parameters in an HTTP request.  This is typically done using AJAX and a static [WebMethod]. 

    Again, it is a lot easier to provide assistance of you take the time to share sample code that illustrates what you are trying to do.  

    Tuesday, September 8, 2020 6:51 PM