Client side script calling Server side functions

Hi, I'm currently developing an ajax.net enabled aspx page that contains a usercontrol (which is based on the listbox but extends it to include icons to represent invalid data).

http://www.djcharlie.co.uk/WeeeCareResolutionCentre.jpg

I want the onClick event of the selected TR to call an asp.net server function which then populates the controls to the right hand side in the page.

Obviously because the row is just rendered HTML overriden from the base class I can only assign a javascript function to the onClick event.

So I need a way of calling a server side function that will populate that will populate the right hand controls from an object based on the row's ID.

I tried playing around with EnablePageMethods after some google-hunting but a) I don't have have that attribute on my scriptmanager (and I have reinstalled the extensions again) and b) apparently it can only call static methods and of course static methods cannot populate controls at page level.

 Thanks in advance,

DJCharlie

0
djcharlie
3/22/2007 2:23:56 PM
asp.net.ajax-discussion 13973 articles. 1 followers. Follow

40 Replies
2209 Views

Similar Articles

[PageSpeed] 44
Get it on Google Play
Get it on Apple App Store

Just to put this in English, you need to get the address data from the database pertaining to the Company that is selected on the left, and update the values in the textboxes on the left with it, without effecting a full postback?  Is that right?

If so, have a look at the xmlhttprequest object in javascript.  This is one of the most straightforward explanations of how to use it, and while the example is classic ASP, you should get the jist.



 


Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
3/22/2007 5:11:59 PM

Is there a reason you're not just using an UpdatePanel to do "partial rendering".  Sure is easier than writing your own Javascript to do what you're describing...

 

--Matt

0
mtimbs
3/22/2007 5:18:11 PM

Matt,

 That would be fine if I didn't have a usercontrol in the picture.  I need to get the click event of the row of the user control to populate another part of the page.

After some research last night it seems the only way I can resolve this is to create a InvalidItem.ascx (row) usercontrol that is a child of the main InvalidItems.ascx control.

This will be made up of a hyperlink containing the company name which upon clicking will use a delegate to raise an event back to the parent control.  In turn, the parent control will raise an event back to the client (the page) and then the page can handle this event appropriately by updating the UpdatePanel containing all the textboxes and storing a Current ID in ViewState.

I am going to crack on with this today, but if anyone else can come up with some other suggestions I would be glad to hear them.

Thanks,

Martin

0
djcharlie
3/23/2007 8:37:25 AM

Matt,

 That would be fine if I didn't have a usercontrol in the picture.  I need to get the click event of the row of the user control to populate another part of the page.

After some research last night it seems the only way I can resolve this is to create a InvalidItem.ascx (row) usercontrol that is a child of the main InvalidItems.ascx control.

This will be made up of a hyperlink containing the company name which upon clicking will use a delegate to raise an event back to the parent control.  In turn, the parent control will raise an event back to the client (the page) and then the page can handle this event appropriately by updating the UpdatePanel containing all the textboxes and storing a Current ID in ViewState.

I am going to crack on with this today, but if anyone else can come up with some other suggestions I would be glad to hear them.

Thanks,

Martin

0
djcharlie
3/23/2007 8:47:08 AM

If you want to use updatepanel for this the following maybe good for you:

Put an updatepanel around your user control, put a hidden input and a dummy button in the user control. When you handle a clienside onclick for an "item" in the user control: put the item's id in the hidden input by javascript, then trigger a click event for the dummy button javascript. Then you get a partial postback, and you will land in the dummy button's server side click event and the hidden input contains the clicked item's id. Now you can rebind/refill etc. other part of the page and call the appropriate updatepanel's update method.

 


 

 

0
stmarti
3/23/2007 9:11:18 AM

Sounds very interesting!

Hidden Input,,, yep, no problem... but whats a dummy button?

Also, how do I put the id of the row clicked into the hidden input control and get the partial postback to occur/trigger the server side event?

Thanks a lot,

Martin Big Smile

0
djcharlie
3/23/2007 9:30:48 AM

Mikesdotnetting,

Thanks it's nice to see what's going on behind the scenes and I think that javascript might come in handy when implementing stmarti's solution.

Cheers,
Martin

0
djcharlie
3/23/2007 9:50:26 AM

Hello,

Some semi-pseudo code maybe it helps (wire also an event on the server side to the "helper" button):

<item id="you'll generate a unique id for this by server side" onclick="test( this );" /> 

<item id="you'll generate a unique id for this by server side" onclick="test( this );" />

<item id="you'll generate a unique id for this by server side" onclick="test( this );" />  ....

<div style="display: none; line-height: 0pt;">
  <asp:HiddenField id="selectedItem" runat="server" />
  <asp:Button id="helper" runat="server" UseSubmitBehavior="false"  />
</div>

The javascript:

function test( sender )
{
    var selectedItem = document.getElementById( "selectedItem" );
    selectedItem.value = sender.id;
    var helperButton = document.getElementById( "helper" );
    helperButton.click( );   
}

 

0
stmarti
3/23/2007 10:15:46 AM

You're a legend! Thanks!!

 

Am going to try and set this up now... if you wanna add me to your msn for aspnet/ajax/wpfe discussions or such like feel free

cook_martinNOSPAM@hotmail.com

obviously remove the NOSPAM ;)

M

0
djcharlie
3/23/2007 10:52:45 AM

Hmmm....

In order to create the necessary number of rows i will have to build them dynamically, and this means having a second control to hold a single item (row)?

Is that right?

M

0
djcharlie
3/23/2007 11:14:12 AM

Just a thought:

Couldn't your user control expose a public event like "RowClicked", and then have an update panel around your content (on the right hand side) and set it to Conditional Update and set it's trigger to the "RowClicked" event of your user control?

0
VR2
3/23/2007 12:38:36 PM
djcharlie:

Hmmm....

In order to create the necessary number of rows i will have to build them dynamically, and this means having a second control to hold a single item (row)?

I doesn't understand this... 

Couldn't your user control expose a public event like "RowClicked", and then have an update panel around your content (on the right hand side) and set it to Conditional Update and set it's trigger to the "RowClicked" event of your user control?

You are right, that could be the server side part of the task, but he asked for how to partially update the "right hand side" using the client side javascript onclick of a "row" as a starting event.

0
stmarti
3/23/2007 12:55:27 PM

Sort of but my point was that adding client side JS was not needed, just have the control's "RowClicked" event be a trigger to the UdpatePanel on the RH side.

To illustrate, I put together:

A Web Site
A Custom Web Control

Here is the Custom Control:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestControls
{
    
    [ToolboxData("&lt;{0}:TestControl runat=server></{0}:TestControl>")]
    public class TestControl : WebControl, INamingContainer
    {
        public class RowClickedEventArgs : EventArgs
        {
            public int RowID;
            public RowClickedEventArgs(int rowID)
            {
                this.RowID = rowID;
            }
        }
        public event EventHandler RowClicked;

        private Button _button;

        protected override void OnInit(EventArgs e)
        {
            _button = new Button();
            _button.ID = "_button";
            _button.Text = "Click Me!"; 
            _button.Click += new EventHandler(_button_Click);

            this.Controls.Add(_button);
            base.OnInit(e);
        }

        void _button_Click(object sender, EventArgs e)
        {
            if (RowClicked != null)
            {
                // Pass off some data in the event args...
                RowClicked(this, new RowClickedEventArgs(5));
            }
        }
    }
}
 

 

And here is the web page ASPX template:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs" Inherits="PageTest" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
         </div>
        <TestControls:TestControl ID="TestControl1" runat="server" Height="84px" Width="165px" OnRowClicked="TestControl1_RowClicked" />
        <asp:UpdatePanel ID="RHUpdatePanel" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Label ID="RHLabel" runat="server"></asp:Label>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="TestControl1" EventName="RowClicked" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>
 

 

"C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs" Inherits="PageTest" %>

And here is the code behind cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class PageTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Nothing to do
    }
    protected void TestControl1_RowClicked(object sender, TestControls.TestControl.RowClickedEventArgs e)
    {
        RHLabel.Text = DateTime.Now.ToLongTimeString() + " and the RowID is: " + e.RowID;
    }
}

 

So, given that you have a control (User Control or Custom) that has a public event, why do you need custom Javascript in order to trigger the update of any update panel you desire, and pass any parameters also?

 

0
VR2
3/23/2007 1:25:07 PM

VR2,

 This is fantastic!!! Thank you!

I am just creating a demo page to fully get to grips with how all this is working and then I will implement it into my solution.

I knew the best method was to use events but was struggling to incorporate this into an AJAX.NET solution.

Thanks again,

Martin Smile

0
djcharlie
3/23/2007 1:31:40 PM

You're most welcome, however I noticed that the post kinda scr3wed with some of the CS code in particular the Generic applied to the EventHandler, it should read:

public event EventHandler<RowClickedEventArgs> RowClicked;

not

public event EventHandler RowClicked;

 

Hope this displays OK & makes sense.

0
VR2
3/23/2007 1:43:15 PM

<TestControls:TestControl ID="TestControl1" runat="server" Height="84px" Width="165px" OnRowClicked="TestControl1_RowClicked" />

I have added all the code from your example but I'm getting the following error at design time on this line: -

Error 6 Unrecognized tag prefix or device filter 'TestControls'

The site will not compile.

Do I need the Register directive?

Thanks,

Martin

 

0
djcharlie
3/23/2007 1:57:47 PM

Yes you do: Smile add this to your Web Config:

<

add tagPrefix="TestControls" namespace="TestControls" assembly="TestControls"/>

Just to be clear, here is the entire thing:

 

<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
	</configSections>
	<system.web>
		<pages>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add tagPrefix="TestControls" namespace="TestControls" assembly="TestControls"/>
      </controls>
		</pages>
		<!--
          Set compilation debug="true" to insert debugging
          symbols into the compiled page. Because this
          affects performance, set this value to true only
          during development.
    -->
		<compilation debug="true">
			<assemblies>
				<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
			</assemblies>
		</compilation>
		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
		</httpHandlers>
		<httpModules>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
		</httpModules>
	</system.web>
	<system.web.extensions>
		<scripting>
			<webServices>
				<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
				<!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
				<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
				<!--
        <authenticationService enabled="true" requireSSL = "true|false"/>
      -->
				<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
				<!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
			</webServices>
			<!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
		</scripting>
	</system.web.extensions>
	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<modules>
			<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
		</modules>
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated"/>
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
		</handlers>
	</system.webServer>
</configuration>
 

0
VR2
3/23/2007 2:12:45 PM

Awesome! Thanks again!!

Still learning... ;)

Martin

0
djcharlie
3/23/2007 2:17:04 PM

<TestControls:TestControl ID="TestControl1" runat="server" Height="84px" Width="165px" OnRowClicked="TestControl1_RowClicked" />

Sorry, it still doesn't like that line.

I now have these messages: -

Error 60 Could not load file or assembly 'TestControls' or one of its dependencies. The system cannot find the file specified.  
Error 74 Element 'TestControl' is not a known element. This can occur if there is a compilation error in the Web.

This is the contents of the ascx file of the TestControl (everything else in the sample i have duplicated exactly)

<%

@ Control Language="C#" AutoEventWireup="true" CodeFile="TestControl.ascx.cs" Inherits="TestControl" %>

Thanks,
Martin

0
djcharlie
3/23/2007 2:25:13 PM

So, given that you have a control (User Control or Custom) that has a public event, why do you need custom Javascript in order to trigger the update of any update panel you desire, and pass any parameters also?"

You are right this works for buttons linkbuttons etc... But the original problem was:

"I want the onClick event of the selected TR to call an asp.net server function which then populates the controls to the right hand side in the page"

I think in that case we need some javascript to trigger and "pass" some row id to the public event of the usercontrol (your great example shows to Martin how to do this) from the TR.
 

0
stmarti
3/23/2007 2:36:43 PM

Yes, it certainly seems that to get the exact solution I originally designed for I will need to incorporate both of these fantastic answers.

Thank you both and I will certainly expose a demo version of the page publically once it is working and perhaps release the source for others to build similar listbox with icons style interfaces.

Thanks again,

Martin

0
djcharlie
3/23/2007 2:42:54 PM

 

PAGETEST.ASPX

<%

@ Page Language="C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs" Inherits="PageTest" %>

<!

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<

html xmlns="http://www.w3.org/1999/xhtml" >

<

head id="Head1" runat="server">

<title>Untitled Page</title>

</

head>

<

body>

<form id="form1" runat="server">

<div>

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

</div>

<TestControls:TestControl ID="TestControl1" runat="server" Height="84px" Width="165px" OnRowClicked="TestControl1_RowClicked" />

<asp:UpdatePanel ID="RHUpdatePanel" runat="server" UpdateMode="Conditional">

<ContentTemplate>

<asp:Label ID="RHLabel" runat="server"></asp:Label>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="TestControl1" EventName="RowClicked" />

</Triggers>

</asp:UpdatePanel>

</form>

</

body>

</

html>

PAGETEST.ASPX.CS

using

System;

using

System.Data;

using

System.Configuration;

using

System.Collections;

using

System.Web;

using

System.Web.Security;

using

System.Web.UI;

using

System.Web.UI.WebControls;

using

System.Web.UI.WebControls.WebParts;

using

System.Web.UI.HtmlControls;

public

partial class PageTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// Nothing to do

}

protected void TestControl1_RowClicked(object sender, TestControls.TestControl.RowClickedEventArgs e)

{

RHLabel.Text =

DateTime.Now.ToLongTimeString() + " and the RowID is: " + e.RowID;

}

}

 

 

TESTCONTROL.ASCX

<%

@ Control Language="C#" AutoEventWireup="true" CodeFile="TestControl.ascx.cs" Inherits="TestControl"%>

 

 TESTCONTROL.ASCX.CS

using System;

using

System.Data;

using

System.Configuration;

using

System.Collections;

using

System.Web;

using

System.Web.Security;

using

System.Web.UI;

using

System.Web.UI.WebControls;

using

System.Web.UI.WebControls.WebParts;

using

System.Web.UI.HtmlControls;

namespace

TestControls

{

[

ToolboxData("&lt;{0}:TestControl runat=server></{0}:TestControl>")]

public partial class TestControl : WebControl, INamingContainer

{

public class RowClickedEventArgs : EventArgs

{

public int RowID;

public RowClickedEventArgs(int rowID)

{

this.RowID = rowID;

}

}

public event EventHandler<RowClickedEventArgs> RowClicked;

private Button _button;

protected override void OnInit(EventArgs e)

{

_button =

new Button();

_button.ID =

"_button";

_button.Text =

"Click Me!";

_button.Click +=

new EventHandler(_button_Click);

this.Controls.Add(_button);

base.OnInit(e);

}

void _button_Click(object sender, EventArgs e)

{

if (RowClicked != null)

{

// Pass off some data in the event args...

RowClicked(

this, new RowClickedEventArgs(5));

}

}

}

}

 

0
djcharlie
3/23/2007 2:57:37 PM

Hmmm...

How do I get it to paste without it doing that? 

Hehe

0
djcharlie
3/23/2007 2:59:05 PM

Re the compilation errors, are you using VWD Express or the full VS 2005?

If it's the former then you need C# Express to Create the Custom Web Control and VWD Express to create the web site (ie NOT in the same solution)

If it's the latter then you can set it up like this:

Create a Web Site (AJAX Enabled)

Add a C# Project of type "Web Control Library" called "TestControls". Add a Class file Called "TestControl" to it and Paste in the code posted earlier.

Modify your web config as advised.

Compile the "TestControls" project. The new "TestControl" is now in your Toolbox. Simply drag it onto a page in your web site. Add a ScriptManager to the page, add the RHUpdatePanel and place a Label inside it. Now goto it's Triggers and set up a trigger ControlID="TestControl1" EventName="RowClicked", then select the "TestControl1" goto the events (lighting bolt) and add a RowClicked handler (as per the cs code posted earlier.

Re the TR click thing - yes I agree that could be another issue - basically you want a plain old HTML TR tag to raise an event at the Server Control it lives in (ie work like a command button). There must be good, easy ways to do this? I'm not sure. I think I'd prefer to keep the "Server Model" and use a Server Side Table instead? Would that solve things? I'll have a think..

0
VR2
3/23/2007 3:01:48 PM

Thanks for the prompt response!!

I am using VS2005.  I think that may be the issue... the Web Controls Library part... just trying it now.

Regarding the TR Click thing, whatever I can use to allow me to do hover over (which changes the bgcolor ie highlight it) and then raises a server side click event that populates based on rowid I'll take! :)

Will get back to you once I have a working model.

Thanks a lot,

Martin

0
djcharlie
3/23/2007 3:07:06 PM

Just a thought: maybe this Page method will come in useful?:

Page.ClientScript.GetCallbackEventReference

Apparently it:

 

        //
        // Summary:
        //     Obtains a reference to a client-side function that, when invoked, initiates
        //     a client call back to server-side events. The client-side function for this
        //     overloaded method includes a specified target, argument, client-side script,
        //     context, error handler, and Boolean value.
        //
        // Parameters:
        //   argument:
        //     An argument passed from the client-side script to the server-side System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(System.String)
        //     method.
        //
        //   context:
        //     Client-side script that is evaluated on the client prior to initiating the
        //     callback. The result of the script is passed back to the client-side event
        //     handler.
        //
        //   clientErrorCallback:
        //     The name of the client-side event handler that receives the result when an
        //     error occurs in the server-side event handler.
        //
        //   target:
        //     The name of a server System.Web.UI.Control that handles the client callback.
        //     The control must implement the System.Web.UI.ICallbackEventHandler interface
        //     and provide a System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(System.String)
        //     method.
        //
        //   useAsync:
        //     true to perform the callback synchronously; false to perform the callback
        //     asynchronously.
        //
        //   clientCallback:
        //     The name of the client-side event handler that receives the result of the
        //     successful server-side event.
        //
        // Returns:
        //     The name of a client-side function that invokes the client callback.
 
0
VR2
3/23/2007 3:37:28 PM

Right, almost cracked the sample page mate...

It recognises the TestControls namespace, and the control therein (woot)

 However, still getting an error on this line..

<

TestControls:TestControl ID="TestControl1" runat="server" Height="84px" Width="165px" OnRowClicked="TestControl1_RowClicked" /> 

Error 59 No overload for 'TestControl1_RowClicked' matches delegate 'System.EventHandler' c:\inetpub\wwwroot\ZeusDotNet\WeeeCare\testing\PageTest.aspx 15 

Thanks,
Martin

0
djcharlie
3/23/2007 3:43:13 PM

Nevermind, sorted it mate!

I copied and pasted the original code and of course that didn't include the <RowClickEventArgs> generic.

Will keep you posted on success over the weekend.

Thanks again,
Martin

0
djcharlie
3/23/2007 4:02:44 PM
Big Smile You see - now I'm so pleased I spotted that (forum bug - does not support Generics in code window??!!)
0
VR2
3/23/2007 4:07:25 PM

 
        protected override void OnInit(EventArgs e)
        {
            _button = new Button();
            _button.ID = "_button";
            _button.Text = "Click Me!";
            _button.Click += new EventHandler(_button_Click);

            this.Controls.Add(_button);
            base.OnInit(e);
        }

How would I extend this functionality so that the button was contained within a fixed control

ie

<TR>

<TD width="100">-button-</TD><TD>-CompanyNameText-</TD><TD>-image-</TD><TD>-image-</TD><TD>-image-</TD><TD>-image-</TD>

</TR>

 To fall inline with this (except with the exception of an edit button or hyperlink)

http://www.djcharlie.co.uk/WeeeCareResolutionCentre.jpg

 

Thanks,

Martin

0
djcharlie
3/23/2007 4:51:25 PM

Nevermind, found out how to do this... Like this! :)

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100");
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            _button.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();
            base.Render(writer);
        }

 
0
djcharlie
3/23/2007 5:14:54 PM

Hi again,

Glad to see you're progressing well but I had a thought: have you considered using a pre-built data control like the GridView or Repeater etc? It might be preferable that writing your controls the way you are? In other words, you'd have a template to work from rather than code everything using the HtmlTextWriter.

Also it would give you databinding, which may help?

Also, thinking about how the gridview works, if you wanted to select a row, you'd press a button which had a CommandName of "Select" (for that row). So I think that you may want that kindof thing but with the button hidden (or better, not there at all) but with that "Button Click" code executing when someone clicks merely on the table row. And that's the question, I think perhaps that method I posted earlier (or one like it) may give you a way to "invoke" the button from your javascript.

 

 

0
VR2
3/23/2007 10:52:00 PM

I have something very similar and hopefully someone can shed some light on this as I'm thinking the discussion so far may encounter this.  I have a user control with a set event that passes a value back to it host page which then shows the value.  This all works except for the fact that AJAX portion is not function how you would think it should.  When ever a button is clicked in the user control it causes a regular postback as if the user control (UC) the holding page were not in an update panel.  To reiterate:

UC with event defined to send a value to the holding page to display something based upon the value passed.

Both UC and page have update panels within each both update modes set to "conditional" and triggers set for the buttons

scriptmanager is set to enableparticalrendering="true"

Unfortunately, even with all this the page will do a complete post back acting like there wasn't any AJAX.  Hope this all makes sense.

Anyone have an idea if AJAX will not function in this sense or if additional steps need to be added?

thanks

^_^

0
bobothebugbear
3/25/2007 6:44:12 AM
Bobo - if you have a separate question, please start a new thread.

Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
3/25/2007 8:49:51 AM

Mikesdotnetting:
Bobo - if you have a separate question, please start a new thread.

Annoying troll.  You'll see how it relates if you read it.

0
bobothebugbear
3/25/2007 7:10:34 PM

I didn't intend to troll or annoy you.  I offered my advice because this thread is now very long, and significantly fewer people will be watching it than any new thread that's started.

I do concede on reflection, that I could have worded my suggestion differently.  That way it might have come across a suggestion instead of a demand.  For that I apologise.


Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
3/25/2007 7:47:51 PM

OK, so back to topic:

 Small example of using arbitrary HTML markup to "invoke" an asp.net server control's postback call (such as a row "click" of a gridview invoking the "Select" for that row?):

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>                
                <asp:Button ID="Button1" Style="display:none;" runat="server" Text="Button" OnClick="Button1_Click" UseSubmitBehavior="False" /> 
            </ContentTemplate>
        </asp:UpdatePanel>
        <div>
            <table border="1" width="400px">
                <tr onmouseover="this.style.backgroundColor='aqua';" onmouseout="this.style.backgroundColor='';" onclick="<%= ClientScript.GetPostBackEventReference(new PostBackOptions(Button1, "")) %>">
                    <td>Row 1
                    </td>
                </tr>
                <tr onmouseover="this.style.backgroundColor='aqua';" onmouseout="this.style.backgroundColor='';" onclick="<%= ClientScript.GetPostBackEventReference(new PostBackOptions(Button1, "")) %>">
                    <td>Row 2
                    </td>
                </tr>
                <tr onmouseover="this.style.backgroundColor='aqua';" onmouseout="this.style.backgroundColor='';" onclick="<%= ClientScript.GetPostBackEventReference(new PostBackOptions(Button1, "")) %>">
                    <td>Row3
                    </td>
                </tr>
            </table>            
        </div>
    </form>
</body>
</html>

 

 CodeBehind:

  

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {        
        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToLongTimeString();
    }
}
 

0
VR2
3/26/2007 8:21:40 AM

OK so a Gridview example of something similar: here I just made the control fields into a template field (so I could specify meaningful names for the buttons). Then I adjusted the onclick of the row using the rowDataBound event callback to throw the row into editmode (simulated the user clicking the Select button for that row):

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button selectButton = e.Row.FindControl("SelectButton") as Button;
        Button editButton   = e.Row.FindControl("EditButton") as Button;

        if (editButton != null)
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(new PostBackOptions(editButton));
        
        e.Row.Style.Add(HtmlTextWriterStyle.Cursor, "default");
    }
}
 
0
VR2
3/26/2007 8:55:45 AM

This is VERY interesting stuff.  I feel kind of guilty as it seems you have spent more time on this than I have (not that I had much choice this weekend.... but thats another story)

So, this line here... It fires server side code on a client side event, is that right?

onclick="<%= ClientScript.GetPostBackEventReference(new PostBackOptions(Button1, "")) %>">

Thanks a lot for your time, I am learning loads!

Martin

0
djcharlie
3/26/2007 10:27:50 AM

You're learning, I'm learing, we're all learning I suspect or we wouldn't be here :)

I'd almost forgotten about this thread but I implemented this in some code I was writing and wanted to mention that the server button my javascript code was "invoking" was set to Visible = false on the server side and this method still worked (I thought it might complain if the button was not visible (rendered) on the page).

I don't know about anyone else but ASP.NET was not that attractive to me pre-atlas: I always found that user interfaces could be much slicker when "Hand coded" with ajax and so on. The approach I came to after many years was simply this:

Copy the way Windows applications / smart clients are written.

That is to say that the notion of "Pages" should be done away with. What should happen, I decided, was that a "Blank page" should be delivered to the browser with only "bootstrapper" javascript code in it and an "Application Launch" object - so the page would look like your dektop - with icons to click on to start applications.

When the user did this, some code would run like this:

var form = safeNew("StockApplication", 640, 480);
form.show();

The "safeNew" would be a method supplied by the bootstrapper that would check that the class existed on the client, and if not would download it from the server (via ajax of course). In addition, the way the classes were wriiten would mean that any dependancies would also be downloaded at this point.

The application would then run and would use web services only to interact with the server.

The upshot was that no GUI was ever delivered to the client, only the code that was needed was downloaded (at a class level granularity) and the only data transfer (after the initial blank page) was for data only, in Json or Xml format.

I found the advatages were too many to count but mainly:

Speed: My god it was fast - small downloads and ultra responsive GUI.

State: finally we could be truly stateful - none of this viewstate nonsense, if you coded something, like an event listener for example, the listener would stay put! An no need to worry about repopulating controls after a postback as you simply never ever posted back.

User Interface: So often when designing applications you want/need a pop up. In HTML land that is tricky, verging on impossible (if you want to fire up a window from an ajax callback). A ClientSide "WinForm" object takes care of all that and you can have as many "Fake" windows as you like, modal or not.

GUI - Finally we could make use of Windows like objects like TreeViews and resizer panels etc etc

Basically you would end up with a "smart client" like a C# Control would give you but the end user would not need .NET, only an Ajax Browser. I decided it gave "The most for the least".

But the cons would include things like accessibility, downgradability and ease of development. Also it was entirely propriatory and outside any established "framework".

I'm rambing now but my point is that because of the architecture of ASP.NET, with it's postbacks and now "Partial" postbacks, it simplifies in one way (via the toolsets) but in another it complicates the hell out of it when you have server classes that get re-instatiated every postback (losing all settings) and with the emphisis on server code, you lose touch of the client side so something as simple as giving a control focus or sending data to the server via javascript (UpdatePanel) takes all this know-how and trickery to accomplish. I'm sure alot of the frustration is because I'm so new to this, learning ASP.NET AND the AJAX components for it at the same time but even so it does seem to me like many things are overly complicated, all for the sake of handling that "onclick" on the server, not the client.

Its almost a shame that Javascript is turn-off-able, and that not all devices support it as if they did then the notion of handling events like that on the server would sound rediculous to most people.

I'm probably not alone when I say that if you want to write an application quickly and easily, you probably reach for the C# application templates because they are so straightforward and "Do what they say on the tin" with none of the "issues" and "gotchas" that seem to surround the world of ASP.NET.

All said and done though, its genuis that the UpdatePanel is so easy to use out of the box AND will downgrade to a full postback if no javascript is present, and in my smart client world that would simply not be possible becasue the server would not know how to render gui (that is a client side function).

One last point about that (I promise) is that I found that often, with a smart client you might want to do something like add a row to a table, via client script. The anology for .NET now would be getting data from a web service, via javascript, and now you want to actually display it on the page. All of a sudden you find youself in a position where you are writing client side code that does exactly the same thing as the server side code (render rows in your table). The Server needs to know how to draw that table, and so does the client. It becomes a duplication of code of the worst kind, you write the same thing, in effect, in two different languages, for two different machines. For example the server (aspx or in-code) might apply a style to the table, might apply certain attributes or handlers to the rows or cells, and your client code, if it wants to add ONE simple row to that table, needs to know how to do all of that exactly as the server did it. Also the server is limited to strings to define everything, like "onclick=DoGlobalFunction()" whereas the client can be much more fanciful using closures and so on to do things like "row.hiddenData = complexClientObject.SubObject" or "$addHandler(row, "click", ComplexClientObject.DoMethod)", there is no need for the objects to be serializable to strings to be assigned.

So the point being that this mixing of server and client code that we do in ASP.NET creates its own set of problems. What I don't think has helped is that much of the client API of ASP.NET AJAX has been pushed out to the CTP (DataServices, xmlScript etc) and documentation for it is practically non-existant. It could be that the next version of Visual Studio and .NET 3 will start to move away from the server postback model and start giving us a proper client side framework so that, if we choose to, we can build "one page" applications in a manner similar to I described. I've seen glimpses of this in the CTP with 2 way databinding of client controls with client side "Datatables" bound to client side "Gridviews" with a client side "Datasource" taking care of the data comms with the server "DataService" but it needed alot of work yet.

 

 

0
VR2
3/31/2007 2:13:29 AM
Reply:

Similar Artilces:

calling server side function from client side script
i have a web form that includes a function named "koko()" in its server side class i want to write a script code in in its HTML script that will be run at the client side, and this client side script will call the function "koko()" from the server side. in brief : i want to call a server side function from a client side script... can you help me in this You can't call server-side code directly from client-side code. You can, however, trigger a postback that your server-side code watches for and triggers the server-side code appropriately. You can do some ...

Call server-side script from client-side script
Hi to all, I would like to ask you How can i call from client-side script a server-side script and to have the result from the server-side script in the client-side script. For example, i wand to call a function writing in server-side (DynaScript) script from a client-side script (JAVASCRIPT) and to have an answer from the function. Thanks in advance. Nick, One way that you could get round this is to write your client script code as you would server script eg. <SCRIPT language=javascript> function getValue()... would be written as: <% psDocument.WriteLn(&...

How to call a client side script from a server side script?
Hi guys, I have a Button1_Click function which gets executed on the server side as soon as Button1 is clicked. I have a client side function, test, which is  written in vbscript. I need to call this test function from the Button1_Click function. Can anyone of you please tell me how to do this? The test function is inside an asp:content tag (Please excuse my terminology if I am wrong, I am new to all this).  Thanks and Regards, RJ Have you tried to use the below code Button1.Attributes.Add("onclick","test()"); HCHaissam Abdul MalakMCAD.NET| Blog | Yes, ...

How do I call server side function in client side script without using __doPostBack
Hello, My page has a server side panel that is hidden when the page loaded, checkboxes inside of the datagrid, and buttons.  If at least one checkbox is not clicked and the user click on the button, I show the panel.  When the user click on one of the checkbox, I want to hide the panel.  Onclick on the checkbox I already have a cleint function to change the row color.  I don't want to use __doPostBack.  Don't want to do postback. My question are: How do I either have checkbox onclick called both client and server side functions.  Or have the client side func...

How to call server side(C#) function from Client side(Javascript) function?
Hi i have used below functions,  function HandleOnClose() {// this function will be called after clicking browsers close button in Internet explorer if (event.clientY < 0) { event.returnValue = 'Are you sure you want to leave the page?'; } // if he clicks ok then i need to call one server side function in this instance.. else not. } <body onbeforeunload="HandleOnClose()" leftmargin="0" rightmargin="0">other controls in page..</div>  How to achieve this? Thanks MS AJAX Extensions would be the option of choice here. Combined with webservices you can...

How to call server side function on client side
Hi,   How to call server side function on client side? here i want to call change() function on textbox onchange event.   <script language="javascript">    function serverfunction()    {    }    </script><input id="Text1" onchange="javascript:serverfunction();"  type="text" /> code behind:  public void change()    {        Response.Write("hello");    } <script type=&quo...

Calling server side scripts from client side
Hello, Can Anyone help out from the following : It is regarding calling server side scripts from client side events. I am able to instantiate a jaguar component in the server side script written in the body of the HTML page as follows : <% var mycomp = java.CreateComponent ("pkg_dispatch/n_jaguar", "iiop://jaguar:9000", "Jagadmin", "" ); if (mycomp == null) { document.writeln("ERROR: failed to instantiate !"); return; } %> I want to use the instance of the jaguar component else wher...

Calling a client side function from the server side
Is it possible to call a client side function from the server side. I dont want to invoke that function through button click. I just want to call that to do some operations.  Regards, Aish Use the below code ASP.NET 2.0 Page.ClientScript.RegisterStartUpScript(this.GetType(),"callfunction","<script language=javascript>Test();</script>"); ASP.NET 1.X Page.RegisterStartUpScript("callfunction","<script language=javascript>Test();</script>"); Where Test() is the javascript function. HCHaissam Abdul MalakMCAD.NET| Blog | No, it is not possible.  The cl...

Is it possible to call client side function from server side code without initial client request?
Atlas is great. I'm using timer to periodically check database changes on server to populate client side controls with new data. Is it possible to do it without a lot of client requests to server which takes a huge useless network traffic? Server should call client side function on all connected clients when, for example, 'database updated' event occurs on server. Thanks. Hi~ Just for your interest, I think you could have a look at Comet, many web IM like Gmail's embeded Gtalk and meebo.com are built on this architecture你好! Just FYI o_O...

Calling server side function from client side alert
Hi, I am developing an ASP.Net application in which I am giving client side alert to the user with OK and Cancel buttons. Can I call a server side function from the click of this button? For e.g. I have to give user alert "Do you want to save record" with Yes/No button. On Yes button click it should go to the server and save the record. Can I call some server side function from the Yes button click? Any help in this regard will be highly appreciated. Thanks in advance. Ashish I would create a button control, say Button1. set Button1.visible=False then, ...

Call client side function from server side code
My problem is that in some point of the VB.Net code I need to call a function defined in vbScript, for example: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click   'There's some code here....   ' ...   If (SomeCondition) Then   'HERE'S WHERE I NEED TO CALL THE JAVASCRIPT FUNCTION... SO HOW CAN I DO THAT?   Else     '...   End If   ' ... End Sub The asp.net code runs to generate the html and when it is done the html is rendered in your browser. So you can't access cli...

Call server side function from client side javascript
I have a javascript where I either need to call an onclick even of a server link button or I need to be able to call a server side function.   The only thing is I cant use AJAX.  Is there any way I can do this or am I spinning my wheels. Thanks!-------------Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue. I have a similar problem.  In my case, I would like to set a server-side session object from JavaScript.  Any suggestions?  Thanks.  Dan Sure, y...

How to Call server side and client side function on same LinkButton
hello,         i have one linkbutton when i click on linkbutton i insert record in DB using onclick=Linkbutton_click. if successfully insert then returnvalue is 1. after return 1 i want to call javascript function. how i can do this? Reply ASAP. Is It Possible? e.g. <asp:LinkButton ID="Operation_Link" runat="server" OnClick="Operation_Link_Click"></asp:LinkButton>protected void Operation_Link_Click(object sender, EventArgs e) {if (Operation_Link.Text == "SUBMIT") {ReturnValue = company.InsertCompany...

Calling a server-side procedure from a client-side function
I have a server side function that executes a database stored procedure, and I need to be able to call it from a javascript function.  Is this possible (without using an iFrame)?  Post back the page or use Ajax. Eric Pascarello.com | Twitter epascarello | LinkedIn...

Web resources about - Client side script calling Server side functions - asp.net.ajax-discussion

Talk:Trigonometric functions - Wikipedia, the free encyclopedia
This article is within the scope of WikiProject Mathematics , a collaborative effort to improve the coverage of Mathematics on Wikipedia. If ...

Four arrested after wedding brawl outside Westella Renaissance function centre
A crowd of people watched on as a violent brawl erupted between two groups outside a wedding reception venue in Sydney's west.

iPhone best tricks and functions - Business Insider
Your iPhone can do a lot more than you think.

Facebook Updates Search Function; Now Is A Great Time To Run And Check All Your Privacy Settings
Facebook search is… well, kind of a joke. It can tell you which 400 people in your area have similar names to that one person you want to connect ...

Review: HP Spectre 360 A Perfect Mix Of Style, Form, Function
HP Inc. delivers a brushed-aluminum laptop with a new 6th Generation Intel i7 processor, making it one of the best-looking, best-priced and best-performing ...

Add ‘laser beam’ to your iPhone’s long list of functions
Whether for presentations or driving your cat up the wall, laser pointers are as fun as they are useful. Given everything else an iPhone can ...

Why Global Corporations Need To Redesign Their Strategic Planning Function
Corporate strategy teams play an important role in guiding business leaders to make smarter, better and more informed decisions, especially in ...

Sponsored post: Garmin’s fenix 3 Pairs Form and Function with GPS Watch
... timepiece to polish off a professional look, or strap on a rugged stopwatch for our workouts. But when it comes to everyday use, the functional ...

Code Craft – Embedding C++: Timing Virtual Functions
... compiler just like the standard language types. A subtype inherits the characteristics of its parent type and can use, or not, the member functions ...

Madras HC asks police to allow Tipu’s birth anniversary function
... Station on a petition filed by Ismail, General Secretary of Thamizhaga Makkal Jananayaga Katchi, seeking grant of permission to hold the function. ...

Resources last updated: 11/30/2015 7:11:18 AM