First, Introduction
First, we note that ASP.net 2.0 also provides a server control ImageMap. This control is a server control that allows you to define a hotspot (HotSpot) area on the picture. Users can either click the Hotspot area for a postback (postback) operation or forward to a URL address. Typically, the control is used to interact with the local scope of a picture. However, the disadvantage of this control is that clicking on these hotspot areas for postback will cause the entire Web page to be refreshed.
In this article, we will extend the normal HTML map control based on ASP.net Ajax technology to meet the Web 2.0 application Development trend When we click on the Hotspot area, and only cause local page updates when the details are displayed.
Figure 1 below shows a snapshot of the sample program at run time.
Figure 1. The map control hotspot with the AJAX technology extension only causes local updates.
As seen above, when the mouse hovers over Jupiter (Jupiter) in the upper solar system, details about the planet are displayed amicably in a pop-up window (note: This figure is taken from MSDN and there is no translation of the corresponding word).
Second, create an AJAX sample Web site
Start Visual Studio 2005, select file → new site ..., then select the asp.net ajax-enabled Web site template, name the project "Ajax_imagemap", and select C # as the built-in support language, and then click OK.
Then, add a new ASPX page imagemap.aspx, and modify the HTML code section as follows:
The following is a reference fragment:
alt= "Solar System" usemap= "#SystemMap" >
<map name= "Systemmap" >
<area shape= "rect" coords= "0,0,82,126"
Onmouseover= "Javascript:getareainfo" (Event, ' Sun '); "onmouseout=" javascript:hidepopup (); >
<area shape= "Circle" coords= "90,58,3"
Onmouseover= "Javascript:getareainfo" (Event, ' Merglobe '); "onmouseout=" Javascript:hidepopup (); "
>
<area SHAPE ... ...... Omitted
</MAP>
In the code above, we added an HTML element and an HTML element (note: The VS2005 toolbar does not provide ready-made controls and can only be added manually). It defines the corresponding hot shape and coordinate information of each planet. Also, each hotspot has a corresponding onmouseover and onmouseout JavaScript function associated with it. When the mouse moves over these hotspots, the two functions are activated and the corresponding information is displayed. For these two functions, we'll discuss them in more detail later.
Third, create an AJAX service
Now we need to create a new Web service that is responsible for data retrieval tasks related to hotspot clicks. In fact, the so-called "Ajax service" here, its function is consistent with the usual Web services. The details of the differences between them are no longer detailed here. Now, you can right-click the project and add a Web service named Locationservice.asmx.
Note that in this example we only want to simulate a simple logic in the combat environment with this Web service. Therefore, it contains only one Web method, which is responsible for simulating the information needed by the client from the server database.
Here, in order for this ASP.net Web service to be invoked from the client in Ajax, the ScriptService attribute must be added to the front of the class declaration, as follows:
The following is a reference fragment:
[ScriptService ()]
PublicclassLocationService:System.Web.Services.WebService
{
Now, write our Web methods:
The following is a reference fragment:
[WebMethod]
[Scriptmethod (Usehttpget=false,responseformat=responseformat.json)]
Publicstringgetareainfo (Stringarea)
{
Returnarea;
}
We typically use HttpPost (or httpget= false) to access Web methods for security reasons, according to the authorities. We then configure the returned data format in JSON format (the default is JSON).
For simplicity, the Getareainfo method here simply returns the same value for the input parameter, but in actual development we should replace it here to retrieve the data from the database.
So far, we have successfully created a Web service that has been invoked from the client in an AJAX fashion.
However, we also need to make some appropriate configuration of the server control ScriptManager in the page, as follows:
The following is a reference fragment:
<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
<services>
<asp:servicereference path= "~/locationservice.asmx"/>
</services>
</asp:ScriptManager>
Here, we only add a service reference under the node, but how does it work?
From the generated HTML source analysis, the configuration above will produce the following:
The following is a reference fragment:
<script src= "Locationservice.asmx/jsdebug" type= "Text/javascript" ></script>
The script tag here refers to a JavaScript file locationservice.asmx/jsdebug. This is actually a Web service proxy class. It is through this proxy class that we are able to invoke the server-side Web services asynchronously from the client.
More interestingly, if you simply copy the path shown above to the browser, you will see a JavaScript file generated by the AJAX environment at run time-this file makes the script service invocation available. As for the proxy class, we will not discuss it further.
Next, let's look at how to create a custom client class.
Create client-side custom classes
We know that one of the major "inventions" of the ASP.net Ajax framework is that it introduces an object-oriented JavaScript programming model. Now, with the help of JavaScript design patterns, we can easily create our own templates or classes, add inheritance concepts, create interfaces and enumerations, and so on.
In this article, we will develop a client class that encapsulates the functionality required in this example.
Now, right click on the project and add a new JavaScript file named ImageMap. In this file, we will define a new namespace myservices, which will contain the client classes we are developing. As shown below:
The following is a reference fragment:
Type.registerNamespace ("MyServices");
Next, we define the constructor of the client class to be created:
The following is a reference fragment:
Myservices.location = function (UIElement, uibody) {
MyServices.Location.initializeBase (this);
This._uielement = UIElement;
This._uibody = Uibody;
This._xaxis = 0;
This._yaxis = 0;
}
The constructor of a template or class is nothing more than a normal JavaScript function. The constructor has a total of two parameters: UIElement and Uibody.
Both of these parameters will be used to describe the pop-up window displayed on the page. The other two private variables _xaxis and _yaxis are used to describe where the pop-up window is displayed. Typically, we'd better declare all the private members in the constructor.
Next, we'll use the prototype design pattern to write the member functions and properties in the class:
The following is a reference fragment:
MyServices.Location.prototype =
{
Get_uielement:function ()
{
return this._uielement;
},
Set_uielement:function (value)
{
This._uielement = value;
},
Get_uibody:function ()
{
return this._uibody;
},
Set_uibody:function (value)
{
This._uibody = value;
},
Note that the UI element property method here is defined in much the same way as a defined form in various languages in. Net.
The following member function is our focus, which is responsible for invoking the remote Web service:
The following is a reference fragment:
Showpopupinfo:function (event, AreaName)
{
MyServices.LocationService.GetAreaInfo (AreaName,
Function.createdelegate (this, this.) oncompleted),
This. OnError,//callback function responsible for error handling
This. OnTimeOut); callback function that is responsible for timeout processing
This._xaxis = Event.clientx;
This._yaxis = Event.clienty;
}
The code above shows a very typical way to invoke a Web service from a client:
1 form is almost as convenient as calling a common local method;
2) The Function.createdelegate function is a very important global function in the development of ASP.net AJAX clients. One of the original purposes of creating this function is to resolve the problem with this keyword. In an event handler that is raised by a DOM element, the This keyword always references this DOM element rather than the class itself. But here, the reason we use this function is to make the AJAX environment invoke the callback function when it succeeds in the same class instance that fires the Web service. This is very important when you need to refer to the properties and methods of the client class. In short, using this function makes it safe and accurate to access the properties and methods of the client class that invokes the Web service. Otherwise, the client class instance that makes the asynchronous call will be NULL because the response of the Web service is executed in a different context-the context no longer equates to the context in which the asynchronous Web call request was issued.
3 Interestingly, the Getareainfo method here is not one of the Web services we created earlier, but a Web service proxy class created at run time-this proxy class accesses the server-side ASMX Web service as a client proxy.
In the last two lines of code in the Showpopupinfo function, the values of two private variables Xaxis and YAxis are set using the input parameters of the event. Our purpose here is to display the pop-up window as close to the user's click position as possible.
Here is the implementation code for the callback function corresponding to the success of the call:
The following is a reference fragment:
Oncompleted:function (result, usercontext, MethodName)
{
var UIElement = $get (This.get_uielement ());
var uibody = $get (This.get_uibody ());
if (uibody!= null)
{
var textnode = Uibody.firstchild;
if (!textnode)
{
Textnode = document.createTextNode (result);
Uibody.appendchild (Textnode);
}
Else
{
Textnode.nodevalue = result;
}
if (UIElement!= null)
{
uiElement.style.visibility = "visible";
UiElement.style.display = "inline";
UiElement.style.left = This._xaxis + "px";
UiElement.style.top = This._yaxis + "px";
}
}
},
The content is fairly simple-set the data returned from the server side to the display of the pop-up window and make sure that the window is displayed as appropriate.
At the end of creating the client class, we must also tell the AJAX framework to register with the client so that it can be accessed from the client:
The following is a reference fragment:
MyServices.Location.registerClass ("Myservices.location");
At this point, the client class Myservices.location has been successfully created. So, how do you use it?
First, we need to define a new instance of the client class when the page loads. To do this, we need to program in the Pageload function:
The following is a reference fragment:
Varlocation=null;
Functionpageload (Sender,args) {
Location=newmyservices.location ("Modal", "modalbody");
Location. Hidepopupinfo ();
}
The code above simply creates a new instance of the Myservices.location class. Then call one of the member functions of the client class to hide the pop-up window in the page. Why do we create an instance of the client class in the Pageload function? The reason is that when the AJAX environment control process arrives at the Pageload function, all AJAX clients and user-defined JavaScript code have been successfully loaded. As a result, we can safely access any user or system-defined JavaScript code at this time.
Several other tool functions are simpler, and are no longer to repeat.
V. Summary
In this article, I showed you how to extend an HTML map control by creating an AJAX service and creating your own custom client class. In an extended control, when you click on an area of the image, we can give the details in a new Ajax way without having to refresh the entire Web page. Although we are less likely to apply this to the map controls in most Web applications (and perhaps therefore omitted from the VS2005 toolbar), a map control based on this AJAX transformation will make your Web application more colorful if you develop a large number of images, images, and map-related Web applications.