Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Passing ASP variable to outside js file

Options
  • 02-11-2007 2:05pm
    #1
    Registered Users Posts: 4,037 ✭✭✭


    I am stuck on this for a couple of days now and it's driving me insane.
    I have a grid on an ASP page and I want to pass the cell that has been selected to a method in an external javascript file.
    I registered the method ("btnFindEmployee_OnClick()") with the DataGrid under the Page Load event:
    DataGrid1.Attributes.Add("onclick", "btnFindEmployee_OnClick()");
    

    I put in an alert box to the method to make sure the method was being called when I click on the grid and it is but I just don't know how to pass the value of the cell that has been selected.
    Any help would be appreciated, thanks.


Comments

  • Registered Users Posts: 2,931 ✭✭✭Ginger


    In your Javascript use the getelementbyID

    Make sure that your Datagrid cells all have IDs assigned and pass in the ID of the cell and use the InnerHTML to get the value of the cell


  • Registered Users Posts: 4,037 ✭✭✭lukin


    I found this link:http://p2p.wrox.com/topic.asp?TOPIC_ID=50874
    (see the code right at the end)
    that is similar to what I want to do, except I changed the javascript to fetch back the value of the label, not set it to a different value.
    It worked perfectly when I put that project together but not when I tried to change it to my own.
    Except when I used it the compiler said that it didn't know what the javascript function I was calling from the button was.


  • Registered Users Posts: 2,931 ✭✭✭Ginger


    Can you post your ASPX code and your code behind file code


  • Registered Users Posts: 4,037 ✭✭✭lukin


    Ginger wrote: »
    Can you post your ASPX code and your code behind file code

    Sure, here's the aspx file (called "deletehotel.aspx").
    <&#37;@ Page Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="DeleteHotel.aspx.cs" Inherits="DeleteHotel" Title="Amend/Delete Hotel" %>
     
        
    <asp:Content ID="Content1" ContentPlaceHolderID="mainContentPlaceHolder" Runat="Server">
         &nbsp; &nbsp; &nbsp;
    
         <asp:Label ID="lblAmendHotel" runat="server" Text="Amend Hotel Details" Width="156px"></asp:Label><br />
        
                   <table border="10" style="width: 68px; height: 67px; border-style:solid; border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid; float: left;" id="tblDetails" title="Hotel Details">
                
                
                <tr>
                    <td style="width: 28px;  border-style:solid;">
                        <asp:Label ID="lblHotelName" runat="server" Text="ID" Width="86px"></asp:Label></td>
                    
                
                    <td style="width: 28px; border-style:solid; height: 37px; border-style:solid;">
                        <asp:Label ID="lblAddress1" runat="server" Text="Hotel Name" Width="79px"></asp:Label></td>
                    <td style="width: 57px; height: 37px; border-style:solid;">
                        <asp:Label ID="Label2" runat="server" Text="County"></asp:Label></td>
                
             
                    <td style="width: 98px; border-top-style: solid; border-right-style: solid; border-left-style: solid;
                        border-bottom-style: solid; height: 7px; border-style:solid;">
                        <asp:Label ID="Label1" runat="server" Text="Address 1" Width="74px"></asp:Label></td>
                    <td style="width: 57px; height: 7px; border-style:solid; border-style:solid;">
                        <asp:Label ID="lblAddress2" runat="server" Text="Address 2" Width="69px"></asp:Label></td>
                </tr>
                
            </table> 
        
        &nbsp;&nbsp;
        <asp:SqlDataSource ID="SqlDataSourceCRS" runat="server" ConnectionString="<%$ ConnectionStrings:CRS_SQLConnectionString %>"
            SelectCommand="SELECT [HotelID], [HotelName], [County], [Address1], [Address2] FROM [Hotel]"></asp:SqlDataSource>
       
        <div style="vertical-align: top; height:100px; width:62%; overflow:auto;">
        
        <asp:DataGrid ID="DataGrid1"  runat="server" DataSourceID="SqlDataSourceCRS" ShowHeader="False" Width="490px" CellPadding="0" BorderStyle="Solid" Height="20px" OnItemDataBound="DataGrid1_ItemDataBound">
            <ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"
                Font-Underline="False" HorizontalAlign="Left" />
            <EditItemStyle BorderStyle="Solid" />
            <Columns> 
                <asp:EditCommandColumn CancelText="Cancel" EditText="Edit" UpdateText="Update" ></asp:EditCommandColumn>
            </Columns>
        </asp:DataGrid>
            </div> 
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick = "button1_onclick"/>&nbsp;
        <asp:TextBox ID="TextBox1" runat="server" Text="test"></asp:TextBox>
      
      <script language= "javascript" type="text/javascript"  src="AjaxClient.js">
    </script>
        </asp:Content>
    

    Even though there is a grid and a table in the code above, I don't use them.
    The only important part really is at the end after the closing </asp:DataGrid> tag.


    I just put a simple text box and button (both inside a contentplaceholder) and tried to display the text in the text box on an alert box (called from a function inside in the javascript file) The text box with text in it is
    ("<asp:TextBox ID="TextBox1" runat="server" Text="test">)
    The button with the javascript function "button1_onclick" being called. button1_onclick is contained in the jscript file ("AjaxClient.js")

    As you can see I reference the "AjaxClient.js" file at the end:
    <script language= "javascript" type="text/javascript" src="AjaxClient.js">
    </script>
    but when I build it it says:

    "ASP.deletehotel_aspx' does not contain a definition for 'button1_onclick'

    The Javascript is
    function button1_onclick(){
    alert("test");
    var x = document.getElementById("ctl00$mainContentPlaceHolder$TextBox1");
    alert(x.innerText);
    }
    

    I'm not even getting the "test" alert to come up as it is not calling the function at all.
    The C# code for the ASPX file is just
    public partial class DeleteHotel : System.Web.UI.Page
    {
    
           protected void Page_Load(object sender, EventArgs e) 
             {
           Page.ClientScript.RegisterClientScriptInclude("xxx", "AjaxClient.js");
             }
    
    }
    
    

    All that is in there is registering the javascript file.


  • Registered Users Posts: 2,931 ✭✭✭Ginger


    Are you just trying to delete a row in the datagrid???


  • Advertisement
  • Moderators, Science, Health & Environment Moderators Posts: 8,950 Mod ✭✭✭✭mewso


    Ah .net and script. So bad. For starters your page is in a masterpage which is fine you just need to be aware that id values will be changed automatically by .net so when you use document.getElementById("button1") or whatever it won't work because the id button1 will have been changed.

    Their are 2 ways to get around this. One is to open the page and view the source. A button with an id of button1 for example will end up with an id of something like mymasterpagename_mycontentpagename_button1. (I notice you have used an id with the $ sign in it. This often indicates you have grabbed the name of the element and not the id from the source) You can take everything up to button1 and make a constant string in your script code like var netAppend = "mymymasterpagename_mycontentpagename_" and then every time you use getElementById(netAppend + "button1"); and so on.

    The other way is to use class values to identify elements on the page:-

    <asp:button id="button1" cssclass="button" .... and so on then in script loop buttons on the page

    var btns = document.getElementsByTagName("input");
    for (i=0;i<btns.length;i++) {
    if (btns.className.indexOf("button")>-1) {
    btns.onclick = button1_onclick;
    }
    }

    This method is ideal if you have functionality to apply to multiple elements so may not serve you here. It should also be used in conjunction with a proper load function for script. I tend to use this method alot especially when it comes to grids and I want to apply something to an onclick event of a button in each row for example. You can use the getElementsByTagname with a table instead of the document for example to limit the amount of looping.

    Also your link to the external .js file should be in head of the masterpage not inline in the page.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    I sorted it eventually. The button on the code in that link was different to mine.
    Once I changed it and got rid of "<asp:Button ID=" and replaced it with what the button in the link looked like, it was then able to call the external jscript function.

    My code (didn't call function):
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick = "button1_onclick"/>&nbsp;
    

    Code on link (did call function):
    <input id="Button1" style="left: 36px; position: absolute; top: 160px" type="button"
            value="html Button1" onclick="button1_onclick()" />
    

    I have a different problem now as I want to use the grid in the same way as I am using the button (ie to pass the value of the grid item selected to the outside jscript function).
    However I want to do it without postback as I want to give it a kind of Ajax-type feel.
    The trouble is that when the the "edit" column is clicked in the grid, (see this line in the code;
    <Columns> 
                <asp:EditCommandColumn CancelText="Cancel" EditText="Edit" UpdateText="Update" ></asp:EditCommandColumn>
            </Columns>
    
    ) then the page automatically refreshes, which I don't want to happen as that is the opposite of what Ajax is for. Is there any way I can prevent this from happening?


  • Moderators, Science, Health & Environment Moderators Posts: 8,950 Mod ✭✭✭✭mewso


    Well as i said above this kind of thing is where using classes as behavious indicators comes into it's own. You can tie one function to any link or button in the grid with a certain class and that function can return false at the end to stop the postback.


  • Registered Users Posts: 2,931 ✭✭✭Ginger


    Your edit button autopostbacks by design.. you can look at the AJax toolkit for .net which would help you along a lot


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    If you want to reference asp.net elements in javascript use code block tags:
    function foo() {
        var button = document.getElementById('<&#37;= Button1.ClientID %>');
        var label = document.getElementById('<%= lblAmendHotel.ClientID %>');
    }
    

    When asp.net renders the page it will insert the client id it generates for you. Its neat and tidy and if you change to a different masterpage (or something) you won't have to update the scripts.

    "ASP.deletehotel_aspx' does not contain a definition for 'button1_onclick'
    Asp.net buttons have an OnClientClick property which you should have a look at, in this case its looking for button1_onclick in the code behind and throwing this error as it can't find it. Move the button1_onlick to the OnClientClick property.

    www.4guysfromrolla.com have some really good datagrid tutorials. GridView, however, would be a far better choice of control imho. Look into TemplateFields.

    And just to be pedantic, Asp and Asp.net are different technologies. I didn't reply to this thread initially as I thought it was Asp, not Asp.net.


  • Advertisement
  • Moderators, Science, Health & Environment Moderators Posts: 8,950 Mod ✭✭✭✭mewso


    Evil Phil wrote: »
    If you want to reference asp.net elements in javascript use code block tags:
    function foo() {
        var button = document.getElementById('<%= Button1.ClientID %>');
        var label = document.getElementById('<%= lblAmendHotel.ClientID %>');
    }
    

    When asp.net renders the page it will insert the client id it generates for you. Its neat and tidy and if you change to a different masterpage (or something) you won't have to update the scripts.

    Neat and tidy if you don't mind having your script in the html page. Each to their own.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Well the main advantage is letting Asp.Net handle the ClientID generation for you (which is what I meant by neat and tidy), after all its generating them anyway. But as you say, each to there own.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    You've deleted that before I could answer, but I'll post this anyways ...

    I'm not sure what you are trying to do. You either A) Want the user to click on the contents of any cell and have this click event call a javascript function passing in an arguement or B) you want an edit (like) button on the grid that you user can click and pass an arguement to the javascript function.

    I've tried both methods with the code below and they worked, the datagrid is bound to a collection of objects which have both a KeywordId property and a Keyword property. The first template column demonstrates A above and I've wrapped the cells contents in an HTML link which calls the function when clicked, and the second demonstrates B. The advantage of the TemplateColumn is that it allows you to put pretty much whatever you like into it. In this code I've used the databinding to populate the value to pass into the javascript function doFoo();

    You should install firefox (if you haven't already) and get the Firebug extension. This will allow you to examine what is going in the rendered html very easily and its a lot better than View - Source :)
    <script type="text/javascript">
        function doFoo(keyword) {
            alert(keyword);
        }
    </script>
    <asp:DataGrid ID="dg1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundColumn DataField="KeywordId" HeaderText="ID">
            </asp:BoundColumn>
            <asp:TemplateColumn HeaderText="Keyword">
                <ItemTemplate>
                    [B]<&#37;--This is the first template column--%>[/B]
                    <a href="javascript:doFoo('<%# DataBinder.Eval(Container.DataItem, "Keyword")%>');">
                        <%# DataBinder.Eval(Container.DataItem, "Keyword")%>
                    </a>
                </ItemTemplate>
            </asp:TemplateColumn>
            <asp:TemplateColumn HeaderText="Button Moon">
                <ItemTemplate>
                    [B]<%--This is the second template column--%>[/B]
                    <input type="button" value="Edit" 
                    onclick="javascript:doFoo('<%# DataBinder.Eval(Container.DataItem, "Keyword")%>');" />                        
                </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>
    


  • Registered Users Posts: 4,037 ✭✭✭lukin


    Sorry Phil, I deleted that response as I found this link (http://www.eggheadcafe.com/articles/20060513.asp) and thought it was was what I wanted but I haven't been able to get that to work so I tried your solution instead.
    It works fine, I moved the jscript to an outside file as there are a lot of other functions that the variable needs to be passed to before I get the AJAX to work the way I want it to.
    The only thing I must change in your code is that the column with the value is there twice. I'll find a way around it hopefully. Thanks again, there's no way I'd have come up with that on my own!


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    No probs, that code really is just for illustrative purposes so chop and change as you need. If you get stuck you know where to ask.

    :)


  • Registered Users Posts: 4,037 ✭✭✭lukin


    I tried everything to remove the extra column but no matter what way I changed the code nothing worked. The only way I could do it was to have a javascript function that removes the content of the cell before the page loads.
    It's not ideal as I have to loop through and find how many entries are in the grid.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Post your code! This should do it for you:
    <script type="text/javascript">
        function doFoo(keyword) {
            alert(keyword);
        }
    </script>
    <asp:DataGrid ID="dg1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundColumn DataField="KeywordId" HeaderText="ID">
            </asp:BoundColumn>
            <asp:TemplateColumn HeaderText="Keyword">
                <ItemTemplate>
                    <%--This is the first template column--%>
                    <a href="javascript:doFoo('<%# DataBinder.Eval(Container.DataItem, "Keyword")%>');">
                        <%# DataBinder.Eval(Container.DataItem, "Keyword")%>
                    </a>
                </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>
    


  • Registered Users Posts: 4,037 ✭✭✭lukin


    Evil Phil wrote: »
    Post your code! This should do it for you:
    <script type="text/javascript">
        function doFoo(keyword) {
            alert(keyword);
        }
    </script>
    <asp:DataGrid ID="dg1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundColumn DataField="KeywordId" HeaderText="ID">
            </asp:BoundColumn>
            <asp:TemplateColumn HeaderText="Keyword">
                <ItemTemplate>
                    <%--This is the first template column--%>
                    <a href="javascript:doFoo('<%# DataBinder.Eval(Container.DataItem, "Keyword")%>');">
                        <%# DataBinder.Eval(Container.DataItem, "Keyword")%>
                    </a>
                </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>
    

    That looks like the same code as you posted before? (I'm in hurry so I could be wrong). I just want to have one column only with the hyper links in it. The code above gives me two.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    The code above should only give you one. Did you read the code or just cut an paste it? I know you're in a hurry but if you take the time to read through both code blocks you'll note the differences.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    That code is still giving me two columns with the numbers in them but it doesn't matter as I fixed it with the help of google where I found some scripts that I changed around to the following:
    function doThis(){
    
    var z=document.getElementById('ctl00_mainContentPlaceHolder_DataGrid1').rows
     var w=document.getElementById('ctl00_mainContentPlaceHolder_DataGrid1').rows.length;  
     var x=0;
     for (x; x <= w; x++)
       {
     var y=z[x].cells
      y[1].innerHTML=""
      
         }
    

    'ctl00_mainContentPlaceHolder_DataGrid1' is the name of the table and the loop above goes down through the second column (which contains the number that I want to delete) and sets each cell to an empty string.
    (Apologies to admins, should prob be in the 'Webmaster' forum).


  • Advertisement
Advertisement