Ajax-based MVC solution in. Net Environment

Source: Internet
Author: User
1. Problem background

Now, more and more people are trying to use Ajax-based Web development. in the. Net environment, Ajax is not very convenient, which may be caused by the following reasons:

· Because Ajax is based on the nature of javascript, developers must have a good understanding of javascript. At least, its javascript capability is sufficient to update pages with callback returned content, therefore, the development threshold increases to a certain extent.

· When developing based on the Ajax mechanism and based on the postback method, asp.net uses the background logic code (Model), aspx page (View), and aspx. the MVC Architecture composed of cs (Controller) actually fails. When callback returns data, it either parses the returned content using javascript on the client side for updates, alternatively, you must construct a relatively complete html code on the server side, and then directly set the constructed html to a page object by javascript. Obviously, as a result, A lot of code is required to implement the simplest callback function, and it is relatively messy code, even in the coming asp. net2.0 still cannot solve this problem effectively

2. Purpose of this Article

This article aims to fully benefit the existing asp.net features and ajax features, and proposes an MVC solution for ajax-based web development in the asp.net environment to achieve the following purposes:

· Clear MVC Architecture for Ajax in Asp. Net Environment

· Reduce the programmer's dependence on excessive javascript code to lower programming barriers

· Flexible support for common development methods in ajax Mode

3. Problem Analysis

How can we achieve the above objectives?

1) xmlhttprequest should be well encapsulated to make the call method simpler;

2) try to construct the updated data on the server side, but avoid manual construction of the data returned each time. Therefore, you can think of using UserControl as "View ", corresponding by ascx. cs files are used as "Controller". The MVC format is clear;
 
4. Problem Solving

Based on the above ideas, I implemented the following group of class libraries to simplify the process:

Download source code and Examples

Code Analysis:

1) first, on the client side, AjaxHelper. js encapsulates xmlhttprequest and provides a function to serialize the existing <form> into a format such as param1 = v1 & param2 = v2 &... parameters used for post;

Updater (ajaxTemplate, output, params, onComplete) functions are used to implement One callback call.

AjaxTemplate (required): Specifies the UserControl path for executing the required functions.
Output (optional): Fill in the reference or ID value of the specified tag for the returned data
Params (optional): form the post parameter such as param1 = v1 & param2 = v2 &...
OnComplete (optional): a callback function that can be used for special processing of returned data. The function format is function (str). str is the returned data.

SerializeForm (form) function for serialization <form>

Form: can be a reference to the specified <form> or ID value

2) on the server side, the Ajax. aspx file encapsulates the call to the UserControl specified by the client ajaxTemplate. Other specific logical functions are implemented in the specific UserControl and its ascx. cs;

3) in this way, when executing a callback operation, programmers only need to reference AjaxHelper on the page. javascript, and call it at the specified position through javascript: Updater (ajaxTemplate, output, params, onComplete). If you need to submit a form, you can call javascript: serializeForm (form) serializes the form and transmits it to params. Of course, you can also manually construct params and specify that the returned data is processed by setting the output application page or using onComplete customization.

4) The full use of UserControl means that the original web server controls and data binding mechanisms of asp.net can be fully utilized. In this way, the structure of returned data has been greatly simplified, in ascx. in cs, Request. form [ParamName] can access the params passed in to the client, and then access the logic code to obtain the source data.

5. Example

The example contained in the source code provides a simple function for retrieving the content of the blog homepage to a textarea without refreshing the content. For details, see the source code!

Some sample source code:

Default. aspx

<% @ Page language = "c #" Codebehind = "Default. aspx. cs" AutoEventWireup = "false" Inherits = "CN. Teddy. AjaxHelper. WebForm1" %>
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<HTML>
<HEAD>
<Title> WebForm1 </title>
<Meta name = "GENERATOR" Content = "Microsoft Visual Studio. NET 7.1">
<Meta name = "CODE_LANGUAGE" Content = "C #">
<Meta name = "vs_defaultClientScript" content = "JavaScript">
<Meta name = "vs_targetSchema" content = "http://schemas.microsoft.com/intellisense/ie5">
<Script type = "text/javascript" language = "javascript" src = "js/AjaxHelper. js"> </script>
</HEAD>
<Body>
<Form id = "Form1" method = "post" runat = "server">
<Div id = "view2"> loading </div>
<Script type = "text/javascript">
Updater ('ajaxtemplate/GetPageSrc ', 'view2', 'url = http://www.cnblogs.com ');
</Script>

</Form>
</Body>
</HTML>

AjaxHelper. js summary:

Var AjaxHelperUrl = new String ("Ajax. aspx ");



Var Updater = function (ajaxTemplate, output, params, onComplete)

{

If (typeof output = 'string ')

{

Output = $ (output );

}



New Ajax. Request ('ajax. aspx ', {onComplete: function (transport) {if (output! = Null) {output. innerHTML = FormatContent (transport. responseText);} if (onComplete! = Null) {onComplete (FormatContent (transport. responseText) },parameters: params + '& AjaxTemplate =' + ajaxTemplate });

}



Var SerializeForm = function (form)

{

Return Form. serialize (form );

}



Var FormatContent = function (str)

{

Var content = new String (str );

Var prefix = new String ("<! -- AjaxContent --> ");

Content = content. substring (content. indexOf (prefix, 0) + prefix. length, content. length-9 );

Return content;

}

UserControl GetPageSrc. ascx. cs Abstract:

Private void Page_Load (object sender, System. EventArgs e)
{
LbUrl. Text = Request. Form ["url"];

System. Net. WebClient client = new System. Net. WebClient ();
Client. Headers. Add ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;. net clr 1.1.4322 )");
Try
{
TxtPageSource. Text = new System. IO. StreamReader (client. OpenRead (lbUrl. Text), System. Text. Encoding. UTF8). ReadToEnd ();
}
Catch (Exception ex)
{
Throw ex;
}
}

Enjoy!

// End the article

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.