Cool UI template technology that can be used with ASP. NET Ajax without updatepanel

Source: Internet
Author: User

[Original address] tip/trick: Cool UI templating technique to use with ASP. NET Ajax for non-updatepanel scenarios
[Original article posting date] Sunday, October 22,200 pm

I have been playing ASP. NET Ajax beta this weekend with great interest.

Usually, when I integrate Ajax functions into my code, I always use ASP. net Ajax provides built-in server-side controls (such as updatepanel and updateprogress) and ASP.. Net Ajax Control Toolkit. Scott hanselman joked two weeks ago in his most recent podcast interview with me that using these Ajax controls is simply "cheating", because in most common scenarios, they do not require any client-side JavaScript code.

This weekend, I decided to focus my programming on ASP. in the net Ajax framework, some client JavaScript library functions of updatepanel are not used at all. In addition, the server is used to generate html ui easily, then, the HTML is dynamically injected into the page through Ajax. In this process, I have created a library that I think is useful. This library can be used with ASP. net Ajax and other Ajax libraries to provide a good ASP. net template UI mechanism, which does not use or require concepts such as PostBack and viewstate, but still provides the advantages of control encapsulation and simple reuse.

First, some brief background knowledge about the JavaScript Network Layer (networking stack) in ASP. NET Ajax

Before starting to discuss the template method I mentioned above, we should first provide some asp. net Ajax client JavaScript library background knowledge, let's first create a simple Ajax "Hello World" application. This application allows users to enter a name, click a button, and then use JavaScript on the client to make an Ajax call to the server, and then output a message:

ASP. NET Ajax contains a very flexible JavaScript Network Library (network library stack), which provides rich serialization support for. NET data types. You can define the methods that can be called from the client JavaScript on the server side, or your asp. NET page class static method, or give your asp. NET application to add a web service, which must be decorated with [Microsoft. web. script. services. scriptservice] metadata attribute, and the displayed method must be decorated with the standard [webmethod] attribute.

For example, the following is a simpleservice. asmx Web Service, which contains a getmessage method that accepts a string parameter:

 

Using system;
Using system. Web. Services;

[Microsoft. Web. Script. Services. scriptservice]
Public class simpleservice: WebService {

[Webmethod]
Public String getmessage (string name ){
Return "Hello <strong>" + name + "</strong>, the time here is:" + datetime. Now. tow.timestring ();
}
}

 

ASP. net ajax can then automatically create a javascript proxy class, which can be used on the client to call this method and pass appropriate parameters. The easiest way to add this JavaScript proxy class is to add an <asp: scriptmanager> control on the page and point it to the Web service endpoint. (This control also ensures that each library is loaded only once on the page .)

Then I can call this method to pass the value in the text box to it, and set a callback event processor with the client JavaScript code like below, which is triggered when the server responds. Note: I can write JavaScript code more fancy and remove several lines.CodeBut at present, I intentionally want to keep it clear and simple to avoid misunderstandings:

 

<HTML>
<Head id = "head1" runat = "server">
<Title> Hello World Service </title>
<Link href = "stylesheet.css" rel = "stylesheet" type = "text/CSS"/>

<Script language = "JavaScript" type = "text/JavaScript">

Function callserver (){
Simpleservice. getmessage ($ get ("name"). Value, displaymessagecallback );
}

Function displaymessagecallback (result ){
$ Get ("message"). innerhtml = result;
}

</SCRIPT>

</Head>
<Body>
<Form ID = "form1" runat = "server">

<Asp: scriptmanager id = "scriptmanager1" runat = "server">
<Services>
<Asp: servicereference Path = "~ /Simpleservice. asmx "/>
</Services>
</ASP: scriptmanager>

<H1> Hello world example
<Div>
Enter name: <input id = "name" type = "text"/>

<A href = "blocked scriptcallserver ()"> call server </a>

<Div id = "message"> </div>
</Div>

</Form>
</Body>
</Html>

 

In this way, when I run this page and enter a name, Scott, the page will use Ajax callback to dynamically update the HTML on the page without any PostBack or page update.

Use a template to generate HTML.

You can see from the above example that I can easily return HTML from the server and inject it into the page on the client. However, one drawback of my practice is that I directly included the HTML generation logic in my server's web method. This is not a good practice, because, 1) mixed UI and logic encoding, 2) as the UI becomes richer, coding will become difficult to maintain and write.

What I want is a simple method. In my web service method, execute my logic and obtain data, then, pass the data to a template or view class to generate the html ui result to be returned. For example, to generate a customer/order management application, use ajax to generate a user list UI like this:

I want to write server-side code like below in my WebService to query customers by country, and then return a suitable HTML list UI. Notice how the following ViewManager. renderview method allows me to upload a data object to bind the UI. All the UI generation codes are removed from my controller webmethod and encapsulated in my view:

 

[Webmethod]
Public String getcustomersbycountry (string country)
{
Customercollection MERs = datacontext. getcustomersbycountry (country );

If (customers. Count> 0)
Return ViewManager. renderview ("MERs. ascx", customers );
Else
Return ViewManager. renderview ("nocustomersfound. ascx ");
}

The result is that this is not very difficult. You only need about 20 lines of code to implement the ViewManager class and the renderview method used above. You can download this simple implementation here.

My implementation allows you to use standard ASP. net user control (. ascx file) model to define a display template, which means you have full vs designer support, intelliisense, and compilation check. It does not require you to use a page to include this user control. In fact, my renderview dynamically generates an empty page object during display to include this user control, record the display and return it as a string.

For example, in the following customer. ascx template, I can use it to output the customer list in the image above. It generates a string of Customer names. Each customer has a connection pointing to their order history details:

 

<% @ Control Language = "C #" codefile = "customers. ascx. cs" inherits = "customers" %>

<Div class = "customers">



</Itemtemplate>
</ASP: repeater>

</Div>

 

The related back-end code is as follows (Note: if I want to, I can add a formatting Method for a specific view to it ):

 

Using system;

Public partial class customers: system. Web. UI. usercontrol
{
Public object data;

Void page_load (Object sender, eventargs E)
{
Repeater1.datasource = data;
Repeater1.databind ();
}
}

 

In order to pass data into the template (for example, the customers set above), I first required each usercontrol to implement an iviewtemplate interface, through which I can associate the data with usercontrol. After playing for a while, I decided to use a simpler user model to show usercontrol a public data attribute as shown above. Then, the ViewManager. renderview method associates the Data Objects passed to it with the usercontrol instance through reflection. Then, the usercontrol behavior is like a normal user control.

The final result is a very powerful and simple method, which can generate any type of HTML response you want and encapsulate it in the. ascx template file very cleanly.

Final Processing

You can download the complete code of the last sample created here. For fun, I added another feature to the above customer list example. After querying by country and returning the customer list, you can click the name of any customer, then a table of orders (and the date on which the orders are placed) is displayed ). This is also implemented using the method described above through Ajax:

The entire application only has 8 lines of JavaScript code on the client, and 15 lines of code (including all the code for data access) on the server ). All html ui generation codes are encapsulated in four. ascx template files. I can load these template files and bind them to my data as needed from my webmethod:

Click here to download the ViewManager. renderview encoding. If you want to see it, try it out.

I hope this article will help you,

Scott

 

Example that can be run after modificationProgram: Ajaxsample

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.