ASP.NET WebForms
|
ASP.NET MVC
|
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.
|
Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
|
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.
|
ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain.
|
The View is called before the Controller.
|
Controller renders View based on actions as a result of the User Interactions on the UI.
|
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.
|
At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
|
WebForms manage state by using view state and server-based controls.
|
ASP.NET MVC does not maintain state information by using view state.
|
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.
|
In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
|
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.
|
A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
|
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.
|
You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
|
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.
|
There is a learning curve to understand the why, when and how of ASP.NET MVC.
|
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.
|
Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
|
Works very well for small teams where focus is on rapid application development
|
Works well for large projects where focus in on testability and maintainability.
|
Sunday, October 21, 2012
How is ASP.NET MVC different from ASP.NET WebForms
Wednesday, October 3, 2012
Anonymous Methods
Delegates are defined as "a reference type that can be used to encapsulate a method with a specific signature"
The use of delegates is involved in event handlers, callbacks, asynchronous calls and multithreading, among other uses.
Before C# 2.0, the only way to use delegates was to use named methods. In some cases, this results in forced creation of classes only for using with delegates. In some cases, these classes and methods are never even invoked directly.
C# 2.0 offers an elegant solution for these methods described above. Anonymous methods allow declaration of inline methods without having to define a named method.
This is very useful, especially in cases where the delegated function requires short and simple code. Anonymous methods can be used anywhere where a delegate type is expected.
Anonymous Method declarations consist of the keyword delegate, an optional parameter list and a statement list enclosed in parenthesis.
Code Snippet: Event Handler (without using anonymous methods)
...
btnSave.Click += new EventHandler (btnSave_Click);
...
void AddClick(object sender, EventArgs e)
{
SaveChanges();
lblStatus.Text = "Your changes have been saved";
}
Code Snippet: Event Handler (using anonymous methods)
btnSave.Click += delegate { SaveChanges(); lblStatus.Text = "Your changes have been saved"; };
Code Snippet: Event Handler using Anonymous Methods, with a parameter list
btnSave.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Text);
SaveChanges();
MessageBox.Show("Your changes have been saved");
}
Anonymous methods can be specified with parameters enclosed in parenthesis, or without parameters, with empty parenthesis. When parameters are specified, the signature of the anonymous method must match the signature of the delegate. When the delegate has no parameters, empty parenthesis are specified in the anonymous method declaration. When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any signature.
Note that method attributes cannot be applied to Anonymous methods. Also, anonymous methods can be added to the invocation list for delegates but can be deleted from the invocation list only if they have been saved to delegates.
An advantage offered with the use of anonymous methods is that they allow access to the local state of the containing function member.
Conclusion
Anonymous methods offer a simple and elegant solution in many situations. In the next version of C#, (C# 3.0), anonymous methods are evolved into Lambda Expressions used in Language Integrated Query (Linq).
Disclaimer
This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof
Thursday, September 20, 2012
3 ways to define a JavaScript class
Introduction
JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.
1. Using a function
This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using thenew
keyword. To define properties and methods for an object created using function()
, you use the this
keyword, as seen in the following example.function Apple (type) { this.type = type; this.color = "red"; this.getInfo = getAppleInfo; } // anti-pattern! keep reading... function getAppleInfo() { return this.color + ' ' + this.type + ' apple'; }
var apple = new Apple('macintosh'); apple.color = "reddish"; alert(apple.getInfo());
1.1. Methods defined internally
In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:function Apple (type) { this.type = type; this.color = "red"; this.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; }
1.2. Methods added to the prototype
A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.function Apple (type) { this.type = type; this.color = "red"; } Apple.prototype.getInfo = function() { return this.color + ' ' + this.type + ' apple'; };
2. Using object literals
Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
var apple = { type: "macintosh", color: "red", getInfo: function () { return this.color + ' ' + this.type + ' apple'; } }
apple.color = "reddish"; alert(apple.getInfo());
3. Singleton using a function
Again with the singleton, eh?The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:
var apple = new function() { this.type = "macintosh"; this.color = "red"; this.getInfo = function () { return this.color + ' ' + this.type + ' apple'; }; }
apple.color = "reddish"; alert(apple.getInfo());
new function(){...}
does two things at the same time: define a function (an anonymous constructor function) and invoke it with new
.
It might look a bit confusing if you're not used to it and it's not too
common, but hey, it's an option, when you really want a constructor
function that you'll use only once and there's no sense of giving it a
name.Summary
You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article's title) there's no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!Friday, September 14, 2012
Combine, Minify and Compress Javascript files to load ASP.net Pages for faster loading
Combine, minify and compress JavaScript files to load ASP.NET pages faster
What is the problem?
After a while you end up referencing to more than a few JavaScript files in your page and that causes a problem! Your pages will load slower; this happens for two reasons:- You have used too much JavaScript. Total size of JavaScript files in some websites may reach more than 500KB and that's a lot, especially for users with slow connections. The best solution to this problem is to use gzip to compress JavaScript files as we do later in this article.
- JavaScript files are loaded one by one after each other by the browser. As you know there is a response time for each request that varies depending on your connection speed and your distance from the server. If you have many JavaScript files in your page these times are added together and cause a big delay when loading a page. I have tried to show this using Firebug (A very popular and necessary FireFox extension for web developers) in the following screenshot.
This is not the case for CSS or image files .If you reference multiple CSS files or images in your page they are loaded together by the browser.
The best solution to this problem is to combine JavaScript files into one big file to remove the delay caused when loading multiple JavaScript files one by one.

What can we do?
The answer is simple! Combine the files and gzip the response. Actually we are going to take few extra steps to create something more useful and reusable. But how we are going to do that?The easiest way to do this is to use an HTTP Handler that combines JavaScript files and compresses the response. So instead of referencing multiple JavaScript files in our pages we reference this handler like this:
- <script type="text/javascript" src="ScriptCombiner.axd?s=Site_Scripts&v=1"></script>
<script type="text/javascript" src="ScriptCombiner.axd?s=Site_Scripts&v=1"></script>ScriptCombiner.axd is our HTTP Handler here. Two parameters are passed to the handler, s and v. s stands for set name and v stands for version. When you make a change in your scripts you need to increase the version so browsers will load the new version not the cached one.
Set Name indicates list of JavaScript files that are processed by this handler. We save the list in a text file inside App_Data folder. The file contains relative paths to JavaScript files that need to be combined. Here is what Site_Scripts.txt file content should look like:
- ~/Scripts/ScriptFile1.js
- ~/Scripts/ScriptFile2.js
~/Scripts/ScriptFile1.js ~/Scripts/ScriptFile2.jsMost of work is done inside the HTTP Handler; I try to summarize what happens in the handler:
- Load the list of paths JavaScript files from the text files specified by the set name.
- Read the content of each file and combine them into one big string that contains all the JavaScript.
- Call Minifier to remove comments and white spaces from the combined JavaScript string.
- Use gzip to compress the result into a smaller size.
- Cache the result for later references so we don't have to do all the processing for each request.
The implementation
I have got most of the code for the handler from Omar Al Zabir article named "HTTP Handler to Combine Multiple Files, Cache and Deliver Compressed Output for Faster Page Load" so most of the credit goes to him.HTTP Handler contains a few helper methods that their purpose is very clear. I try to describe each shortly.
CanGZip method checks if the browser can support gzip and returns true in that case.
- private bool CanGZip(HttpRequest request)
- {
- string acceptEncoding = request.Headers["Accept-Encoding"];
- if (!string.IsNullOrEmpty(acceptEncoding) &&
- (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
- return true;
- return false;
- }
private bool CanGZip(HttpRequest request) { string acceptEncoding = request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"))) return true; return false; }WriteBytes writes the combined and compresses bytes to the response output. We need to set different content type for response based on if we support gzip or not. The other important part of this method sets the caching policy for the response which tells the browser to cache the response for CACHE_DURATION amount of time.
- private void WriteBytes(byte[] bytes, bool isCompressed)
- {
- HttpResponse response = context.Response;
- response.AppendHeader("Content-Length", bytes.Length.ToString());
- response.ContentType = "application/x-javascript";
- if (isCompressed)
- response.AppendHeader("Content-Encoding", "gzip");
- else
- response.AppendHeader("Content-Encoding", "utf-8");
- context.Response.Cache.SetCacheability(HttpCacheability.Public);
- context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
- context.Response.Cache.SetMaxAge(CACHE_DURATION);
- response.ContentEncoding = Encoding.Unicode;
- response.OutputStream.Write(bytes, 0, bytes.Length);
- response.Flush();
- }
private void WriteBytes(byte[] bytes, bool isCompressed) { HttpResponse response = context.Response; response.AppendHeader("Content-Length", bytes.Length.ToString()); response.ContentType = "application/x-javascript"; if (isCompressed) response.AppendHeader("Content-Encoding", "gzip"); else response.AppendHeader("Content-Encoding", "utf-8"); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION)); context.Response.Cache.SetMaxAge(CACHE_DURATION); response.ContentEncoding = Encoding.Unicode; response.OutputStream.Write(bytes, 0, bytes.Length); response.Flush(); }WriteFromCache checks if we have the combined script cached in memory, if so we write it to response and return true.
- private bool WriteFromCache(string setName, string version, bool isCompressed)
- {
- byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[];
- if (responseBytes == null || responseBytes.Length == 0)
- return false;
- this.WriteBytes(responseBytes, isCompressed);
- return true;
- }
private bool WriteFromCache(string setName, string version, bool isCompressed) { byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[]; if (responseBytes == null || responseBytes.Length == 0) return false; this.WriteBytes(responseBytes, isCompressed); return true; }But most of the work is done inside ProcessRequest method. First we take a look at the method and I will try to explain important parts.
- public void ProcessRequest(HttpContext context)
- {
- this.context = context;
- HttpRequest request = context.Request;
- // Read setName, version from query string
- string setName = request["s"] ?? string.Empty;
- string version = request["v"] ?? string.Empty;
- // Decide if browser supports compressed response
- bool isCompressed = this.CanGZip(context.Request);
- // If the set has already been cached, write the response directly from
- // cache. Otherwise generate the response and cache it
- if (!this.WriteFromCache(setName, version, isCompressed))
- {
- using (MemoryStream memoryStream = new MemoryStream(8092))
- {
- // Decide regular stream or gzip stream based on whether the response can be compressed or not
- using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream)
- {
- // Read the files into one big string
- StringBuilder allScripts = new StringBuilder();
- foreach (string fileName in GetScriptFileNames(setName))
- allScripts.Append(File.ReadAllText(context.Server.MapPath(fileName)));
- // Minify the combined script files and remove comments and white spaces
- var minifier = new JavaScriptMinifier();
- string minified = minifier.Minify(allScripts.ToString());
- // Send minfied string to output stream
- byte[] bts = Encoding.UTF8.GetBytes(minified);
- writer.Write(bts, 0, bts.Length);
- }
- // Cache the combined response so that it can be directly written
- // in subsequent calls
- byte[] responseBytes = memoryStream.ToArray();
- context.Cache.Insert(GetCacheKey(setName, version, isCompressed),
- responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- CACHE_DURATION);
- // Generate the response
- this.WriteBytes(responseBytes, isCompressed);
- }
- }
- }
public void ProcessRequest(HttpContext context) { this.context = context; HttpRequest request = context.Request; // Read setName, version from query string string setName = request["s"] ?? string.Empty; string version = request["v"] ?? string.Empty; // Decide if browser supports compressed response bool isCompressed = this.CanGZip(context.Request); // If the set has already been cached, write the response directly from // cache. Otherwise generate the response and cache it if (!this.WriteFromCache(setName, version, isCompressed)) { using (MemoryStream memoryStream = new MemoryStream(8092)) { // Decide regular stream or gzip stream based on whether the response can be compressed or not using (Stream writer = isCompressed ? (Stream)(new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memoryStream)) : memoryStream) { // Read the files into one big string StringBuilder allScripts = new StringBuilder(); foreach (string fileName in GetScriptFileNames(setName)) allScripts.Append(File.ReadAllText(context.Server.MapPath(fileName))); // Minify the combined script files and remove comments and white spaces var minifier = new JavaScriptMinifier(); string minified = minifier.Minify(allScripts.ToString()); // Send minfied string to output stream byte[] bts = Encoding.UTF8.GetBytes(minified); writer.Write(bts, 0, bts.Length); } // Cache the combined response so that it can be directly written // in subsequent calls byte[] responseBytes = memoryStream.ToArray(); context.Cache.Insert(GetCacheKey(setName, version, isCompressed), responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION); // Generate the response this.WriteBytes(responseBytes, isCompressed); } } }this.WriteFromCache(setName, version, isCompressed) returns true if we have the response cached in memory. It actually writes the data from cache to the response and returns true so we don’t need to take any extra steps.
MemoryStream is used to hold compressed bytes in the memory. In case that browser does not support gzip no compression is done over bytes.
We use SharpZipLib to do the compression. This free library does gzip compression slightly better than .NET. You can easily use .NET compression by replacing line 20 with the following code:
- using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream)
using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream)GetScriptFileNames is a static method that returns a string array of JavaScript file paths in the set name. We will use this method for another purpose that we discuss it later.
JavaScriptMinifier class holds the code for Douglas Crockford JavaScript Minfier. Minifer removes comments and white spaces from JavaScript and results in a smaller size. You can download the latest version from http://www.crockford.com/javascript/jsmin.html.
After we wrote minified and compressed scripts to MemoryStream we insert them into cache so we don’t need to take all these steps for each request. And finally we write the compressed bytes to the response.
Make it a little better
We can take one extra step to make the whole process a little better an easier to use. We can add a static method to our handler that generates JavaScript reference tag. We can make this even better by doing different actions when application is running in debug or release mode. In debug mode we usually don’t want to combine our JavaScript files to track error easier, so we output reference to original files and generate all JavaScript references as if we have included in our page manually.- public static string GetScriptTags(string setName, int version)
- {
- string result = null;
- #if (DEBUG)
- foreach (string fileName in GetScriptFileNames(setName))
- {
- result += String.Format("\n<script type=\"text/javascript\" src=\"{0}?v={1}\"></script>", VirtualPathUtility.ToAbsolute(fileName), version);
- }
- #else
- result += String.Format("<script type=\"text/javascript\" src=\"ScriptCombiner.axd?s={0}&v={1}\"></script>", setName, version);
- #endif
- return result;
- }
public static string GetScriptTags(string setName, int version) { string result = null; #if (DEBUG) foreach (string fileName in GetScriptFileNames(setName)) { result += String.Format("\n<script type=\"text/javascript\" src=\"{0}?v={1}\"></script>", VirtualPathUtility.ToAbsolute(fileName), version); } #else result += String.Format("<script type=\"text/javascript\" src=\"ScriptCombiner.axd?s={0}&v={1}\"></script>", setName, version); #endif return result; }GetScriptFileNames as described before returns an array of file names for a specified set.
- // private helper method that return an array of file names inside the text file stored in App_Data folder
- private static string[] GetScriptFileNames(string setName)
- {
- var scripts = new System.Collections.Generic.List<string>();
- string setPath = HttpContext.Current.Server.MapPath(String.Format("~/App_Data/{0}.txt", setName));
- using (var setDefinition = File.OpenText(setPath))
- {
- string fileName = null;
- while (setDefinition.Peek() >= 0)
- {
- fileName = setDefinition.ReadLine();
- if (!String.IsNullOrEmpty(fileName))
- scripts.Add(fileName);
- }
- }
- return scripts.ToArray();
- }
// private helper method that return an array of file names inside the text file stored in App_Data folder private static string[] GetScriptFileNames(string setName) { var scripts = new System.Collections.Generic.List<string>(); string setPath = HttpContext.Current.Server.MapPath(String.Format("~/App_Data/{0}.txt", setName)); using (var setDefinition = File.OpenText(setPath)) { string fileName = null; while (setDefinition.Peek() >= 0) { fileName = setDefinition.ReadLine(); if (!String.IsNullOrEmpty(fileName)) scripts.Add(fileName); } } return scripts.ToArray(); }
- <%= ScriptCombiner.GetScriptTags("Site_Scripts", 1) %>
<%= ScriptCombiner.GetScriptTags("Site_Scripts", 1) %>So whenever we want to reference a handler in an ASP.NET page we only need to add the following tag inside the head section of our page:
There is a final step you need to take before making all this work. You need to add HTTP Handler to Web.config of your website. To do so make the following changes to your web.config file:
- <configuration>
- <system.web>
- <httpHandlers>
- <add verb="POST,GET" path="ScriptCombiner.axd" type="ScriptCombiner, App_Code"/>
- </httpHandlers>
- </system.web>
- <!-- IIS 7.0 only -->
- <system.webServer>
- <handlers>
- <add name="ScriptCombiner" verb="POST,GET" path="ScriptCombiner.axd" preCondition="integratedMode" type="ScriptCombiner, App_Code"/>
- </handlers>
- </system.webServer>
- </configuration>
<configuration> <system.web> <httpHandlers> <add verb="POST,GET" path="ScriptCombiner.axd" type="ScriptCombiner, App_Code"/> </httpHandlers> </system.web> <!-- IIS 7.0 only --> <system.webServer> <handlers> <add name="ScriptCombiner" verb="POST,GET" path="ScriptCombiner.axd" preCondition="integratedMode" type="ScriptCombiner, App_Code"/> </handlers> </system.webServer> </configuration>
Sunday, September 9, 2012
List View Sql Paging
This is a light wait paging that increase the performance of you page.
to create this page i have taken one listview on each next/prev commend i am submitting the page and fatch the records based on the clicked event.
Basically i have used top exection query to show only respective records. below is my code will may be helps you.
using (SqlConnection Sqlcon = new SqlConnection(ConnectionString().ToString())) { int Num = Take - Record; string Sql = "Select top " + Record + " * from tempPage where NOT Pageid IN (Select top " + Num + " Pageid from tempPage)"; Sqlcon.Open(); SqlCommand Sqlcmd = new SqlCommand(Sql, Sqlcon); SqlDataReader Sqldr = Sqlcmd.ExecuteReader(); if (Sqldr != null) { dtList.DataSource = Sqldr; dtList.DataBind(); } Sql = "Select Count(*) from tempPage"; if (Sqlcon.State == ConnectionState.Open) Sqlcon.Close(); Sqlcon.Open(); SqlCommand SqlCmd = new SqlCommand(Sql, Sqlcon); int TotRecord = Convert.ToInt32(SqlCmd.ExecuteScalar()); lbtnNext.Visible = (TotRecord > (Take)) ? true : false; lbtnPrev.Visible = (Take <= Record) ? false : true; }
to download the source code click here
Tuesday, September 4, 2012
Trim in Javaascript
Trim string in Javascript
One simple way of trimming a string is to make use of a powerful regular
expression—as opposed to iterating and removing the space characters
one by one. To see how this works, save the code below as an .htm file, and
then load the file into IE. Click in the text field and then tab out of it to
see the code in action.
<script type="text/javascript">
function TrimString()
{
var txtObj = document.getElementById("txtTrim");
txtObj.value = txtObj.value.replace(/^\s+/,""); //Left trim
txtObj.value = txtObj.value.replace(/\s+$/,""); //Right trim
//
<input type="text" id="txtTrim" onblur="TrimString(this.value);" /
>
}
</script>
Regular Expration via Javascript
<script type="text/javascript"> var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-] {0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i var ck_username = /^[A-Za-z0-9_]{1,20}$/; var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/; function validate(form){ var name = form.name.value; var email = form.email.value; var username = form.username.value; var password = form.password.value; var gender = form.gender.value; var errors = []; if (!ck_name.test(name)) { errors[errors.length] = "You valid Name ."; } if (!ck_email.test(email)) { errors[errors.length] = "You must enter a valid email address."; } if (!ck_username.test(username)) { errors[errors.length] = "You valid UserName no special
char ."; } if (!ck_password.test(password)) { errors[errors.length] = "You must enter a valid Password "; } if (gender==0) { errors[errors.length] = "Select Gender"; } if (errors.length > 0) { reportErrors(errors); return false; } return true; } function reportErrors(errors){ var msg = "Please Enter Valide Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } </script>
jQuery – Reverse Each
jQuery(jQuery(
'div.child'
).get().reverse()).each(
function
(i) {
//do stuff
});
<
div
class
=
"parent"
>
<
div
class
=
"child"
>A</
div
>
<
div
class
=
"child"
>B</
div
>
<
div
class
=
"child"
>C</
div
>
</
div
>