Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Thursday, September 18, 2008

ASP .NET Validators don’t work properly with Update Panel

Recently I am working on a project ASP .NET AJAX. Of course it is very common to have some validators in some forms to control the input values, and unfortunately I experienced problem with validators inside the Update Panel. The validators just don’t work properly as I am expected.

After google searching and here is the solution that I had found: ASP .NET AJAX Validators.

Firstly, downloads the validators.zip file and adds in the DLL into the /bin directory of your project. After that, include the following codes into the pages section of the web.config.

<tagMapping>
  <
add tagType="System.Web.UI.WebControls.CompareValidator" mappedTagType="Sample.Web.UI.Compatibility.CompareValidator, Validators, Version=1.0.0.0"/>
  <
add tagType="System.Web.UI.WebControls.CustomValidator" mappedTagType="Sample.Web.UI.Compatibility.CustomValidator, Validators, Version=1.0.0.0"/>
  <
add tagType="System.Web.UI.WebControls.RangeValidator" mappedTagType="Sample.Web.UI.Compatibility.RangeValidator, Validators, Version=1.0.0.0"/>
  <
add tagType="System.Web.UI.WebControls.RegularExpressionValidator" mappedTagType="Sample.Web.UI.Compatibility.RegularExpressionValidator, Validators, Version=1.0.0.0"/>
  <
add tagType="System.Web.UI.WebControls.RequiredFieldValidator" mappedTagType="Sample.Web.UI.Compatibility.RequiredFieldValidator, Validators, Version=1.0.0.0"/>
  <
add tagType="System.Web.UI.WebControls.ValidationSummary" mappedTagType="Sample.Web.UI.Compatibility.ValidationSummary, Validators, Version=1.0.0.0"/>
</
tagMapping>


And the problem solved. Cheers!

Friday, July 25, 2008

How to Call Remote Web Services from Client Side JavaScript

Web Services is a collection of universally available functions, which allows different applications from different sources to share among each other without time-consuming custom coding by using the XML, SOAP, WSDL and UDDI open standards across the Internet. You can go to here for more detail explanation on it.

Recently, I have been doing some research into how to call a web service from client side JavaScript. ASP .NET AJAX enables you to call a web service from the browser by using client script, namely the page can call server-based methods without a postback and refreshing the whole web page.

Here, I will show you how to call Web Services within the same project and also how to call Web Services remotely.

Consuming a Local Web Service
Simple example of Web Service
I assume that you had installed the ASP .NET AJAX framework. So let us start with create a new ASP .NET AJAX-Enabled Web Application created.

I will firstly show you how to call a web service within the same project, so let’s add new Web Service called webService.asmx to the project (Right-click your project on your solution explorer | Add New Item | Select Web Service and name it | Click Add.).

Let us create a very simple web service that returns current date and time.

In order to make a web service accessible from script, the web service class must be qualified with the ScriptServiceAttribute. See the example below:

...
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
  ...
  [WebMethod]
  public string GetCurrentDateTime() {
    string curTime = String.Format("Current datetime is {0}.", DateTime.Now);
    return curTime;
  }
}


And then save it.

Exposing Web Services to Client Script in .aspx Web Page
To enable a web service to be called from client script in your .aspx file, make sure that we have one instance of ScriptManager object.

Then add the Services collection to the ScriptManager object, reference the web service by adding asp:ServiceReference child element to the Services collection and sets its Path attribute to point to the web service. Below is how it is looks like:

<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Services>
      <asp:ServiceReference Path="WebService.asmx" />
      </Services>
    </asp:ScriptManager>
  </form>
</body>


Client-side Function, Button and Label
Next we need to add in a client-side function to call server-side web service, a button to trigger the web service, and a label to display the returned result. Below is the sample of the web page:

<html>
<head runat="server">
<title>Calling Web Services</title>
<script language="javascript" type="text/javascript">
function GetTime() {
  WebService.GetCurrentDateTime(ShowResult);
}

function ShowResult(result) {
  document.getElementById("lblResult").innerHTML = result.value;
}
</script>
</head>
<body>
  <form id="form1" runat="server">
    ...
    <asp:Label id="lblResult" runat="server">Result will be displayed here.</asp:Label>
    <br/>
    <button id="btn" name="btn" onclick="GetTime()">Get Time</button&gt;
    <br/>
  </form>
</body>
</html>


TIPS: If you want to call the JavaScript function from a separate .js file, copy the functions into the .js file, and the add in Scripts collection to the ScriptManager object, reference the JavaScript function by adding asp:ScriptReference child element to the Scripts collection and sets its Path attribute to point to the JavaScript, as below:

<Scripts>
<asp:ScriptReference Path="CallWebServiceMethods.js" />
</Scripts>


That’s it for consuming web service, which located in the same project.


Consuming Web Services Remotely
WebService Behavior (HTC file)
The first thing that you need to do is to create a separate ASP .NET Web Service application and copy the web service that we created as above into it. I will add another method here to show you how to call a web service and pass parameters to its method through JavaScript.

[WebMethod]
public string EchoYourWord(string yourword) {
  return "You have said that: " + yourword;
}


Save and run it. So now you got your web service ready to test.

WebService behavior enables us to make a method call to a remote web service using a scripted language. It is a reusable DHTML component that uses web services by handling the communication of the SOAP data packets between the browser and the web services.

The following are 3 important methods supported by the web service behavior:
  • createUseOptions – Allows us to preserve authentication information across remote method invocations. Can be very useful when using SSL to communicate with the remote web service
  • callService – Allows us to invoke the remote web service method asynchronously
  • useService – Allows us to establish a friendly name for the web service that can be used while invoking the web service
You can download the HTC file at here. Copy into the same folder as your project.

How to use Web Service Behavior in .aspx Page
I will recommend you that to create another new .aspx page to test on consuming remote web service.

To invoke the GetCurrentDateTime() method, we have to attach the HTC file to a valid element, such as DIV or BODY.

<div id="service" style="BEHAVIOR:url(webservice.htc)" ></div>

Once this behavior is attached, we may need to add some code to the web page to enable use of WebService behavior and make calls to the web service.

Add in this JavaScript function, as below:

function Init() {
  // initialize and create a name "webService" for Web service
  // Note: the "service.use..." is the DIV or BODY element’s id as created just now.
  service.useService("http://localhost/My_WebServices/WebService.asmx?wsdl", "webService");
}


Next, we will need to invoke the useService method in the onload event to map the web service before any methods on the web service are invoked.

After that, we can add in another JavaScript function and use the callService method to invoke the remote web service method asynchronously.

Your web page should look like this when you are done:

<html>
<head runat="server">
<title>Calling Web Services</title>
<script language="javascript" type="text/javascript">
function Init() {
  // initialize and create a shortcut name "webService" for Web service
  // Note: the "service.use..." is the DIV or BODY element’s id as created just now.
  service.useService("http://localhost/My_WebServices/WebService.asmx?wsdl", "webService");
}

function GetTime() {
  // Note: the "service.webService..." is the shortcut name of your web service that you had initialize in the Init().
  service.webService.callService(ShowResult, "GetCurrentDateTime");
}

// sample of passing a parameter to the web service
var myword;
function Echo() {
  myword = document.form1.SayOutLoud.value;
  service.webService.callService(ShowResult, "EchoYourWord", myword);
}

function ShowResult(result) {
  document.getElementById("lblResult").innerHTML = result.value;
}
</script>
</head>
<body onload="Init()">
  <form id="form1" runat="server">
    <div id="service" style="BEHAVIOR:url(webservice.htc)" ></div>
    <asp:Label id="lblResult" runat="server">Result will be displayed here.</asp:Label>
    <br/><br/>
    Your words : <input type="text" name="SayOutLoud"/><br/><br/>
    <button id="btn" name="btn" onclick="GetTime()">Get Time</button><br />
    <button id="btn1" name="btn1" onclick="Echo()">Echo Your Word</button><br/>
    <br/>
  </form>
</body>
</html>


Note: Of course, if you are using a separate .js file, you still need to add a reference in a ScriptManager object, as I had mentioned above.

That’s it for calling a remote web service. Any question please feels free to ask.

Cheers!

Wednesday, June 4, 2008

JavaScript not firing with UpdatePanel

Yesterday when I am dealt with textbox inside an UpdatePanel, I noticed that the JavaScript is not fire when the TextChanged handler is triggered.

I had the code lines as below to fire my JavaScript function.

string strScript = "javascript:alert('Testing')";
ClientScript.RegisterStartupScript(typeof(Page),"clientScript", strScript);


After working around with the bug, finally I found the cause. The ClientScript.RegisterStartupScript is just cannot working within an UpdatePanel. To work around the problem there are related static methods in the class ScriptManager that should be used when the control is used inside an UpdatePanel, as the following:

string strScript = "javascript: alert('Testing')";
ScriptManager.RegisterStartupScript(this.gridPanel, this.GetType(), "strScript", strScript, true);


In short, when you are using UpdatePanel in your form, don’t use ClientScript.RegisterStartupScript. More information please refers to:
http://asp.net/AJAX/Documentation/Live/mref/O_T_System_Web_UI_ScriptManager_RegisterStartupScript.aspx http://asp.net/AJAX/Documentation/Live/mref/M_System_Web_UI_ScriptManager_RegisterStartupScript_5_d03cd23f.aspx

Hope this can help you anyway. Cheers.

Friday, May 30, 2008

How to call Server Side Methods from Client Side Script in ASP .NET

Basically, you cannot call server side methods from client side script directly. Server side methods will execute at server side, client side script at client side, they live at two different worlds.

However, to call a server side method from client side, you can pass some information to the server as a request for an action, which can trigger a code behind method.

One simple solution to communicate with server from client side is to provide a hidden input field to store some flag or information and to read them on the server side.

To achieve this, put a hidden field in your HTML on the page, which use to store some flag. And in the code behind, you can call to the correct method that is needed according to the provided information.

<input id="hiddenVal" type="hidden" value="0" name="hiddenVal" runat="server"/>

Alternatively, you can put a hidden input button in your HTML on the page and then use script to call the button’s click method, as shown below:

<input type="button" id="btnHidden" style="DISPLAY:none" runat="server" onserverclick="server_side_handler"/>

Here is the sample of script to make the button clicks.

var btnHide = document.getElementById("btnHidden");
btnHide.click();


Another way to call a server side method from client side script is by using ASP .NET AJAX Extensions. I assume that you already installed ASP .NET AJAX Extension, and then create a new ASP .NET AJAX-Enabled Web Site. The steps below will show you how this can be done.

Drag and drop a button into the page. The markup will look familiar to the following:

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
    <div>
        <asp:Button ID="btnGetMe" runat="server" Text="Button" />
    </div>
</form>


Add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>

Note: This is very important or else you won’t be able to call the server side methods.

After that, add in a STATIC method to code behind of the page. This method then can be called from client side script easily. Mark the method as a WebMethod to expose the method, as below:

[System.Web.Services.WebMethod]
public static string HelloWorld(string value)
{
    return value;
}


Next step that you need to do is to call the page method. To call the method, you can specify a client-side method. The returned value from the server side will be passed as an argument to the client-side method.

<script type="text/javascript">
function CallMethod()
{
    PageMethods.HelloWorld("Hello, how are you today?", OnSucceeded);
}

function OnSucceeded(result)
{
    alert(result);
}
</script>


To invoke the method whenever the button is clicked, add these few lines of code in the Page_Load() event.

if (!Page.IsPostBack)
{
    btnGetMe.Attributes.Add("onclick", "javascript:CallMyPageMethod()");
}


Try to run your website now.
 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template