Only by truly entering the ASP. net mvc world can we know its highlights.
"Abandon WebService and use jquery to call WCF in. net4." -- after abandoning WebService, you can also use jquery to call controller of ASP. net mvc.
"ASP. net mvc is not required for Ajax-based applications." ASP. net mvc is needed in the Ajax world.
A naive idea proves its innocence in practice, but what we get from innocence to fact is growth.
Let's talk about how I realized this. The process is more important than the conclusion.
Taking the short message function in the blog site in the previous article (displaying the current user's Short Message list) as an example, we started to use the jquery plug-in templates for list data binding. Then we encountered two problems:
1) different elements need to be generated according to the condition when binding. For example, if a user sends a short message, the sender is displayed as a link, and if it is a system notification, the sender is displayed as a text. Templates is not very convenient to handle such operations;
2) The bound data cannot be reused on the server. Sometimes, from the perspective of Friendly search engines or user experience, Ajax is not used when the page is loaded for the first time. Ajax is used only when the page is loaded and clicked to refresh or pagination links. In this way, you need to maintain the data binding operation on the server and the client separately.
That is to say, the server returns the Object Class Object List, and now it returns a string that assembles the data with HTML.
1. At first, we considered an ugly method. We used stringbuilder to concatenate strings to generate data binding results.CodeAs follows:
Obviously, this method is prone to errors and has poor maintainability.
2. Next, we consider the second method (refer to self-render user control as string template) to generate a string through Web user control. The code in the WCF Service is as follows:
Page = New Page ();
Control = Page. loadcontrol ( " ~ /Controls/msglistcontrol. ascx " );
(Irenderable < List < Sitemsg > ) Control). populatedata (sitemsglist );
Stringbuilder sb = New Stringbuilder ();
Using (Stringwriter SW = New Stringwriter (SB ))
{
Using (Htmltextwriter HTW = New Htmltextwriter (SW ))
{
Control. rendercontrol (HTW );
Return SB. tostring ();
}
}
Because the msglistcontrol. ascx type is generated by dynamic compilation, you cannot convert the control to the msglistcontrol type by force type conversion, and then pass the data to it.
Here we need to use another irenderable <t> interface to bind data. msglistcontrol implements this interface. The Code is as follows:
Public Partial Class Msglistcontrol: usercontrol, irenderable < List < Sitemsg >
{
Public Void Populatedata (list < Sitemsg > Sitemsglist)
{
Rptmsglist. datasource = Sitemsglist;
Rptmsglist. databind ();
}
}
Public Interface Irenderable < T >
{
Void Populatedata (t data );
}
In the WCF Service, you can call the populatedata method in the interface to bind data.
This method adds additional interfaces, which is somewhat complicated.
3. Later we thought of ASP. net mvc. Although not familiar with it, we should try to see if it can better solve this problem.
So we can use razor to access ASP. net mvc 3.
Application scenarios:Apply ASP. Net MVC 3 to the existing vs2010 web site project. After msgcontroller receives the request, inbox (an action) returns the entire page view containing the short message list to the client. When a user clicks the page refresh or paging link, a POST request is initiated through ajax to obtain the short message list. After msgcontroller receives the request, list (an action) returns the view of the Short Message list to the client.
Expected results:The short message list view can be reused. inbox and list use the same view.
At the beginning, I encountered two minor problems:
A) After maproute is configured" HTTP Error 404.0-not found "error. The reason is that the accessed URL has no file name and does not go through the ASP. NET pipeline. The solution is to add the following configuration in system. WebServer of Web. config:
<ValidationValidateintegratedmodeconfiguration= "False" />
<ModulesRunallmanagedmodulesforallrequests= "True" />
B) Continue the access. The error "The resource cannot be found." is returned. Solution: Because the web site project is used, you need to move the controllers folder to app_code.
Then, enter the MVC-related code and start with the Ajax call section.
The Controller code is as follows:
Public Class Msgcontroller: Controller
{
[Httppost]
Public Actionresult list (sitemsgquery msgquery)
{
List < Sitemsg > Sitemsglist = Getinboxmsglist (msgquery );
Return View ( " Msglist " , Sitemsglist );
}
}
Note the following: [httppost]. Since it is an Ajax call, you must certainly respond to the POST request.
View code (msglist. cshtml:
@ Using cnblogs. uchome. externalservice. msgwcfservice
@ Model List < Sitemsg >
@ Foreach (sitemsg MSG in Model ){
< Div Class = "Msg_item" >
< Div Class = "Msg_sender" > @ Msg. sendername </ Div >
< Div Class = "Msg_title" > < A Href = '/MSG/item/@ msg. ID /' > @ MSG. Subject </ A > </ Div >
< Div Class = "Msg_sendtime" > @ Msg. sendtime. tostring ("yyyy-mm-dd hh: mm ") </ Div >
</ Div >
}
It is much easier to write than in. ascx.
The client JS call code is as follows:
Function Getmsglist (pageindex, pagesize ){
VaR Msgquery = {}
Msgquery. pageindex = Pageindex;
Msgquery. pagesize = Pagesize;
$. Ajaxsettings. datatype = ' Plain/Text ' ; // Do not use JSON
$. Ajaxsettings. url = ' /MSG/List ' ;
$. Ajaxsettings. Data = ' {"Msgquery ": ' + JSON. stringify (msgquery) + ' } ' ;
$. Ajaxsettings. Success = Function (Data ){
$ ( " # Msg_list " Pai.html (data );
};
$. Ajax ();
}
Note that the server controller does not return JSON data ):
A) datatype should not use JSON, and jquery should be used by default. If so, plain/text should be used;
B) The returned data is in data and cannot be obtained through data. D.
In this way, Ajax calls can be easily implemented using ASP. net mvc, which is more convenient than the previous WCF, stringbuider, And. ascx.
Originally, it was so convenient to use Ajax in ASP. net mvc that it could completely replace the previously used WCF Transfer Station.
Solved the Ajax problem, and then processed the display of the entire page.
Simply reuse the view used by Ajax in the view on the page. The sample code is as follows:
View (inbox. cshtml ):
<! Doctype html >
< Html >
< Head >
< Title > </ Title >
</ Head >
< Body >
@ Html. Partial ("msglist ")
</ Body >
</ Html >
Control:
Public Class Msgcontroller: Controller
{
Public Actionresult inbox ()
{
Sitemsgquery msgquery = New Sitemsgquery ()
{
Pageindex = 1 ,
Pagesize = 30
};
List < Sitemsg > Sitemsglist = Getinboxmsglist (msgquery );
Return View ( " Inbox " , Sitemsglist );
}
}
Done! It's really convenient! The solution is ASP. net mvc!
I am sorry for my incorrect opinion that "ASP. NET MVC is not required for Ajax-based applications! Thank you for your understanding!
Study hard. If you do not enter, you will leave!