ASP.NET Issue

Associate
Joined
13 Jan 2007
Posts
2,424
Location
Belfast,Northern Ireland
Basically I have an int variable in my .aspx.cs file (Code-behind), I want to access this variable in the Javascript part of my .aspx file....how the hell do I do this?

from reading around its suggested it should be var a = "<%codebehindvar%>";

this is proving extremely unsuccessful, any bright ideas pretty please?
 
Change it to :
var a = <%=codebehindvar%>;


<%%> takes a block of code, and you need to explicitly write to the response to render anything into the html. <%= %> takes an expression and prints out the value directly.

I tried various ways with this method in terms of "", '', =, everything and couldnt get it to work. I read of the hidden form method but frankly that sounds horribly messy, must be a simpler way?
 
It's in a protected method but I did think this could be the problem and switched it to public, no luck, the class itself was always public. Here is the compilation error, there are no other errors in the build and everything works fine when i set the variable directly.

Code:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'subsectionscount' does not exist in the current context

Source Error:

Line 107:
Line 108:    <script type="text/javascript">
Line 109:        var sectionId = '<%=subsectionscount%>';
Line 110:        $('#addSection').click(function(evt) {
Line 111:            evt.stopPropagation();


Source File: c:\Users\Test\Desktop\MM Project\trunk\FuriousGadget\FuriousGadget\Edit.aspx    Line: 109

Code-behind file
Code:
namespace FuriousGadget
{
    public partial class Edit : BasePage
    {
        private Article selectedArticle;

        private int ArticleId { get; set; }



        public void Page_Load(object sender, EventArgs e)
        {
            ArticleId = Convert.ToInt32(Request["ArticleId"]);
            Load_Content();
        }

        public void Load_Content()
        {
            
            //Add db context
            var context = new FuriousDatabaseDataClassesDataContext();
            //Dummy writer data

            selectedArticle = context.Articles.SingleOrDefault(u => u.ArticleId == ArticleId);
            var writer = context.Writers.SingleOrDefault(u => u.WriterId == selectedArticle.FK_WriterId);

            var subsections=context.SubSections.Where(u => u.FK_ArticleId == ArticleId);
            subsectionsRepeater.DataSource = subsections;
            subsectionsRepeater.DataBind();
            var images = context.Images.Where(u => u.FK_ArticleId == ArticleId);
            int imagecount = context.Images.Where(u => u.FK_ArticleId == ArticleId).Count();
        [U]   [B] int subsectionscount = context.SubSections.Where(u => u.FK_ArticleId == ArticleId).Count();[/B][/U]
            imagesRepeater.DataSource = images;             
            imagesRepeater.DataBind();
            authtitle.Text = writer.Title;
            authfirstname.Text = writer.Forename;
            authsurname.Text = writer.Surname;
            articletitle.Text = selectedArticle.Title;
            introduction.Text = selectedArticle.Intorduction;
            Page.DataBind();
            //string authforename = writer.Forename;
            //string authsurname = writer.Surname;
            //string intro = selectedArticle.Intorduction;

            //_authtitle.DataBinding = authtitle;
            

            //selectedSubsection = context.SubSections.All(u => u.FK_ArticleId == art.ArticleId);




           




        }

    }
}

Dirty .aspx file
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Edit.aspx.cs" Inherits="FuriousGadget.Edit"
    MasterPageFile="Default.Master" %>

<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
    <article class="post">
                <header>
                    <h3>Edit Post </h3>
                </header>
    <asp:Label runat="server"  ID="errorLabel" />
    <form id="form1" runat="server">
    <div id="DivAuthor">
       <h2> Author</h2>
       <div id="authorarea">
       <div class="label">
        Title:</div>
        <div class="item">
         <asp:Label ID="authtitle" runat="server" name="authtitle"/>
         
                    
        </div>

    <div class="label">
        Forename:</div>
     <div class="item">
        <asp:Label ID="authfirstname" runat="server"/>
        
        </div>
     <div class="label">
        surname:</div>
     <div class="item">
        <asp:Label ID="authsurname"  runat="server" />
        
        </div>
        </div>
        </div>
        <div id="Divarticle">
       <h2> Article</h2>
       <div id="ArticleArea">
    <div class="label">
        Title:</div>
    <div class="item">
        <asp:TextBox ID="articletitle" runat="server" />
        </div>
    <div class="label">
        Introduction:</div>
    <div class="item">
        <asp:TextBox ID="introduction" name="introduction" TextMode="Multiline" Columns="75"
            Rows="10" runat="server" />
        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Text="Required!"
            ControlToValidate="introduction">
        </asp:RequiredFieldValidator></div></div>--%>
    <div id="sectionArea">
        <h2>
            Sections</h2>
            <asp:Repeater id="subsectionsRepeater" runat="server">
             <ItemTemplate>
        <div id="sectionInsertArea">
            <div class="label">
                Subtitle:</div>
            <div class="item">
                <asp:TextBox ID="subtitle1" text='<%#Eval("Subtitle")%>' runat="server" name="subtitle1" />
                <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Text="Required!"
                    ControlToValidate="subtitle1">
                </asp:RequiredFieldValidator>--%>
            </div>
            <div class="label">
                Section:</div>
            <div class="item">
                <asp:TextBox ID="section1" name="section1" text='<%#Eval("Text")%>' TextMode="Multiline" Columns="75" Rows="10"
                    runat="server" />
                <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" Text="Required!"
                    ControlToValidate="section1">
                </asp:RequiredFieldValidator>--%>
                <br />
            </div>
        </div>
        </ItemTemplate>
        </asp:Repeater>
        <div id="addSectionDiv" class="addition clearfix">
            <a href="#" id="addSection">Add Another Section</a>
        </div>
    </div>
    <div id="images">
       <h2> Images</h2>
       <asp:Repeater id="imagesRepeater" runat="server">
             <ItemTemplate>
        <div id="imagesInsertArea">
            <div class="label">
                Image 1: </div>
            <div class="item">            
                <asp:FileUpload ID="image1" runat="server" name="image1"/>
                <asp:Image ID="imageview" runat="server" ImageUrl='<%#Eval("Source")%>' name="imageview" />
                <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" Text="Required!"
                    ControlToValidate="image1">
                </asp:RequiredFieldValidator>--%>
            </div>
        </div>
        </ItemTemplate>
        </asp:Repeater>
        <div id="addImageDiv" class="addition clearfix">
            <a href="#" id="addImage">Add Another Image</a>
        </div>
    </div>
    <%--<asp:Button ID="Submit" runat="server" OnClick="Submit_Clicked" Text="Submit" CssClass="submit" />--%><br />
    </form>
    </article>

    <script type="text/javascript">
     [U]  [B] var sectionId = '<%=subsectionscount%>';[/B][/U]
        $('#addSection').click(function(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            sectionId++;
            $("#sectionInsertArea").append(' <div class="label">Subtitle: </div><div class="item"><input id="subtitle' + sectionId + '" name="subtitle' + sectionId + '" type="text" /></div><div class="label">Section:</div><div><textarea id="section' + sectionId + '" name="section' + sectionId + '" cols="75" rows="10"></textarea></div>');
            BindFocus();
            if (sectionId == 10) {
                $('#addSectionDiv').html('');
            }
        });
        var imageCount = 1;
        $('#addImage').click(function(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            imageCount++;
            $("#imagesInsertArea").append(' <div class="label">Image ' + imageCount + ': </div><div class="item"><input type="file" name="image' + imageCount + '" /></div>');
            if (imageCount == 5) {
                $('#addImageDiv').html('');
            }
        });
        function BindFocus() {
            $('input[type=text], textarea').unbind();
            $('input[type=text], textarea').focus(function(item) {
                $('.focus').each(function() {
                    $(this).removeClass("focus");
                });
                $(item.currentTarget).addClass("focus");
            });
            $('input[type=text], textarea').addClass("unfocus");
        }
        BindFocus();

        $("input[type=submit]").mousedown(function() {
            $(this).css({'background-position':'top left',
                        'padding-bottom':'2px'});
                    }).mouseup(function() {
                    $(this).css({ 'background-position': 'bottom right',
                        'padding-bottom': '3px'
                    });
                });
                $("input[type=submit]").hover(function() {
                    $(this).addClass('buttonfocus');
                }, function() {
                    $(this).removeClass('buttonfocus');
                })
        
    
    </script>

</asp:content>
 
That explains it. Your variable, subsectionscount, is only a local variable inside the Load_Content() method, so it only exists on the stack of the executing thread, while the method is running.

You need to pull it up and make it a class member, and either make it protected or expose it in a protected/public property if you want to render it directly into the html.

Yeah my apologies, my comp at home didn't give many meaningful highlights, as soon as I went in the labs and the variable was greyed out I realised how big a retard I was being.

Thanks for the help
 
Back
Top Bottom