New Features in ASP.NET AJAX 4, Part 2
Instantiating Behaviors and Controls Declaratively
ASP.NET AJAX 4 introduces a way to declaratively instantiate client-side controls and behaviors and attach them to HTML elements. The declarative markup is achieved without adding any new HTML elements, simply by including additional namespaced attributes which are XHTML compliant.
Declarative Instantiation Within a Template
Suppose that you want to add a Contoso.DatePicker control to a div element. In ASP.NET AJAX 4, you can start by declaring a namespace prefix in the opening <body> tag (or in a template's parent tag), similar to the way the @ Register directive works in server-based files. The following example shows a namespace declaration.
<body xmlns:sys="javascript:Sys" xmlns:datepicker="javascript:Contoso.DatePicker">
The javascript:Sys namespace (typically mapped to the sys: prefix, as shown in the example) is used for a number of system attributes. One of those system attributes is sys:attach, which is used to specify a comma-separated list of controls or behaviors to attach to the element, as shown in the following example:
<ul id="myTemplate" class="sys-template">
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
<div sys:attach="datepicker" datepicker:date="{{ CreatedDate }}"></div>
</li>
</ul>
The example shows how to instantiate a Contoso.DatePicker control that is attached to a div element and how to set the control's date property to the value of the CreatedDate field of the current data item.
Declarative Instantiation Outside a Template
Declarative instantiation of controls will only work if the declarative markup is within an element that has been configured, or activated, for this purpose. Templates themselves are already activated, so declarative markup to instantiate and attach controls works within a template. But to declaratively instantiate controls outside a template, you must first configure the page to ensure that sys:attach markup is within an activated element. You do this by including a sys:activate attribute on the opening body tag, and setting its value to a comma-separated list of element IDs for the elements that you want to allow declarative instantiation in. The following example activates elements whose IDs are panel1 and panel2:
<body xmlns:sys="javascript:Sys" sys:activate="panel1,panel2">
This causes the ASP.NET AJAX framework to scan the children of those elements for any sys:attach attributes, and to instantiate the corresponding controls.
You can also activate every element in the document. However, doing so can cause a small delay when the page is initialized, so the technique should be used with caution on large pages. The following example shows how to activate the whole document.
<body xmlns:sys="javascript:Sys" sys:activate="*">
A DataView control is typically attached to an element that is not already within a template. This is a common reason to use sys:activate, as in the following complete example:
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
<ul sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
</body>
Live Data Binding
The template examples shown earlier include several examples of data binding that uses the one-way/one-time binding syntax: {{ expression }}. This is illustrated by the following example:
<h3>{{ Name }}</h3>
This type of binding is referred to as one-time binding because the expression is evaluated only once, at the time that the template is rendered. With one-way/one-time binding, if the source data changes after the template has been rendered (in the previous example, if the Name field changes), the rendered value will not be automatically updated.
You can use an alternative live-binding syntax in order to ensure that the target value is automatically updated whenever the source value changes. This is shown in the following example:
<h3>{binding Name}</h3>
With this binding syntax, if the Name field of the current data item is changed, the rendered value will automatically be updated in response.
This example, where the binding is to a text node (the content of the h3 element), illustrates one-way live binding. The source value (in this case, the data) binds one-way to the target (in this case, an HTML text node), so when the source value changes, the target is updated. But there is no binding from the target back to the source.
Another form of live binding is two-way live binding, which is useful when a text box is provided that enables users to modify the value of underlying data, as in the following example:
<input type="text" value="{binding Name}"/>
In two-way live binding, the binding works in both directions. If the target value is changed (in this case, the value in the UI), the source value is automatically updated (in this case, the underlying data item). Similarly, if the source value is changed (in this case, if the underlying data value is updated externally), the target value (the value in the UI) is updated in response. As a result, target and source are always in sync.
In the following example, if the user modifies the value in the text box, the value that is rendered in the h3 element will automatically be updated to reflect the new value that is provided by the user.
<h3>{{ binding Name }}</h3>
<input type="text" value="{binding Name}"/>
The live-binding syntax is similar to binding syntax in WPF (XAML). It can be used for binding between UI and data, as in the above examples, as well as directly between UI elements, between data and properties of declaratively attached controls and components, and so on. The syntax also supports additional features, such as providing functions for converting data values to rendered values, or converting back from values entered in UI to an appropriately formatted data value. The following example shows how to provide conversion functions:
<input type="text" value="{binding Price, convert=toDollars, convertBack=fromDollars}"/>
A similar syntax can be used to specify a binding mode (one-way or two-way) explicitly:
<input type="text" value="{binding Price, mode=oneWay}"/>
However, in most cases this is not necessary, because the default binding behavior is that text boxes and other input controls automatically use two-way binding, and other bindings use one-way binding. In the previous example, this default behavior is overridden so that if the data value changes, the value in the text box will change, but if the user modifies the value in the UI, the underlying data value will not be updated correspondingly.
The underlying technology that enables live bindings is the ASP.NET AJAX observer pattern, which is used internally by the Binding class and is described in the next section. For more information about binding, see The DataView Control later in this document.
Using the Observer Pattern with JavaScript Objects and Arrays
The observer pattern enables an object to be notified about changes that occur in another object. (The term observer pattern is often misused in JavaScript frameworks to describe event handling based on the addHandler method and similar techniques.) ASP.NET AJAX 4 implements the pattern completely. It adds observer functionality to ordinary JavaScript objects or arrays so that they raise change notifications when they are modified through the Sys.Observer interface. (In the present state of JavaScript, changes that are made directly, without going through the interface, will not raise change notifications.) The observer pattern can be used to establish live bindings between UI elements and objects or arrays, such as those you might get from a JSON Web service.
In the following example, the Sys.Observer class is used to add items to the imagesArray array in a way that raises CollectionChanged notifications. As a result, the DataView control will automatically update and display the inserted item after the user has clicked the Insert button. This is possible because the DataView control is bound to its source data (in this case, the imagesArray array that the data property is set to) by using live binding.
<script type="text/javascript">
var imagesArray = [];
Sys.Observer.makeObservable(imageArray);
function onInsert() {
var newImage = { Name: "Name", Description: "Description" };
imagesArray.add(newImage);
}
</script>
<button onclick="onInsert()">Insert</button>
<ul id="imagesList" sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
Posted in: asp.net | Tags: asp.net asp.net 4.0 asp.net ajax ajax instantiation declarative xmlns declarative instantiation javascript live data binding observer patternVisual Studio 2010 Web Designer Improvements
The Web page designer in Visual Studio 2010 has been enhanced for greater CSS compatibility, includes additional support for HTML and ASP.NET markup snippets, and features a redesigned version of IntelliSense for JScript.
Improved CSS Compatibility
The Visual Web Developer designer in Visual Studio 2010 has been updated to improve CSS 2.1 standards compliance. The designer better preserves integrity of the HTML source and has greater overall robustness than in previous versions of Visual Studio. Under the hood, architectural improvements have also been made that will better enable future enhancements in rendering, layout, and serviceability.
HTML and JScript Snippets
In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes entire tags and more. In Visual Studio 2010, IntelliSense snippets are supported for JScript, alongside C# and Visual Basic, which were supported in earlier versions of Visual Studio.
Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat="server") and common attributes specific to a tag (such as ID, DataSourceID, ControlToValidate, and Text).
You can download additional snippets, or you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks.
JScript IntelliSense Enhancements
In Visual 2010, JScript IntelliSense has been redesigned to provide an even richer editing experience. IntelliSense now recognizes objects that have been dynamically generated by methods such as registerNamespace and by similar techniques used by other JavaScript frameworks. Performance has been improved to analyze large libraries of script and to display IntelliSense with little or no processing delay. Compatibility has been dramatically increased to support nearly all third-party libraries and to support diverse coding styles. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense.
Posted in: programming software | Tags: .net 4.0 javascript visual studio 2010 html.editrofor web designer improvements html and jscript snippets css compatibility datasourceid controltovalidate jscript intellisense registernamespace intellisenseTop 50 JavaScript & AJAX interview questions
1. Why so JavaScript and Java have similar name?
A. JavaScript is a stripped-down version of Java
B. JavaScript's syntax is loosely based on Java's
C. They both originated on the island of Java
D. None of the above
2. When a user views a page containing a JavaScript program, which machine actually executes the script?
A. The User's machine running a Web browser
B. The Web server
C. A central machine deep within Netscape's corporate offices
D. None of the above
3. ______ JavaScript is also called client-side JavaScript.
A. Microsoft
B. Navigator
C. LiveWire
D. Native
4. __________ JavaScript is also called server-side JavaScript.
A. Microsoft
B. Navigator
C. LiveWire
D. Native
5. What are variables used for in JavaScript Programs?
A. Storing numbers, dates, or other values
B. Varying randomly
C. Causing high-school algebra flashbacks
D. None of the above
6. _____ JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation.
A. Client-side
B. Server-side
C. Local
D. Native
7. What should appear at the very end of your JavaScript?
The <script LANGUAGE="JavaScript">tag
A. The </script>
B. The <script>
C. The END statement
D. None of the above
8. Which of the following can't be done with client-side JavaScript?
A. Validating a form
B. Sending a form's contents by email
C. Storing the form's contents to a database file on the server
D. None of the above
9. Which of the following are capabilities of functions in JavaScript?
A. Return a value
B. Accept parameters and Return a value
C. Accept parameters
D. None of the above
10. Which of the following is not a valid JavaScript variable name?
A. 2names
B. _first_and_last_names
C. FirstAndLast
D. None of the above
11. ______ tag is an extension to HTML that can enclose any number of JavaScript statements.
A. <SCRIPT>
B. <BODY>
C. <HEAD>
D. <TITLE>
12. How does JavaScript store dates in a date object?
A. The number of milliseconds since January 1st, 1970
B. The number of days since January 1st, 1900
C. The number of seconds since Netscape's public stock offering.
D. None of the above
13. Which of the following attribute can hold the JavaScript version?
A. LANGUAGE
B. SCRIPT
C. VERSION
D. None of the above
14. What is the correct JavaScript syntax to write "Hello World"?
A. System.out.println("Hello World")
B. println ("Hello World")
C. document.write("Hello World")
D. response.write("Hello World")
15. Which of the following way can be used to indicate the LANGUAGE attribute?
A. <LANGUAGE="JavaScriptVersion">
B. <SCRIPT LANGUAGE="JavaScriptVersion">
C. <SCRIPT LANGUAGE="JavaScriptVersion"> JavaScript statements…</SCRIPT>
D. <SCRIPT LANGUAGE="JavaScriptVersion"!> JavaScript statements…</SCRIPT>
16. Inside which HTML element do we put the JavaScript?
A. <js>
B. <scripting>
C. <script>
D. <javascript>
17. What is the correct syntax for referring to an external script called " abc.js"?
A. <script href=" abc.js">
B. <script name=" abc.js">
C. <script src=" abc.js">
D. None of the above
18. Which types of image maps can be used with JavaScript?
A. Server-side image maps
B. Client-side image maps
C. Server-side image maps and Client-side image maps
D. None of the above
19. Which of the following navigator object properties is the same in both Netscape and IE?
A. navigator.appCodeName
B. navigator.appName
C. navigator.appVersion
D. None of the above
20. Which is the correct way to write a JavaScript array?
A. var txt = new Array(1:"tim",2:"kim",3:"jim")
B. var txt = new Array:1=("tim")2=("kim")3=("jim")
C. var txt = new Array("tim","kim","jim")
D. var txt = new Array="tim","kim","jim"
21. What does the <noscript> tag do?
A. Enclose text to be displayed by non-JavaScript browsers.
B. Prevents scripts on the page from executing.
C. Describes certain low-budget movies.
D. None of the above
22. If para1 is the DOM object for a paragraph, what is the correct syntax to change the text within the paragraph?
A. "New Text"?
B. para1.value="New Text";
C. para1.firstChild.nodeValue= "New Text";
D. para1.nodeValue="New Text";
23. JavaScript entities start with _______ and end with _________.
A. Semicolon, colon
B. Semicolon, Ampersand
C. Ampersand, colon
D. Ampersand, semicolon
24. Which of the following best describes JavaScript?
A. a low-level programming language.
B. a scripting language precompiled in the browser.
C. a compiled scripting language.
D. an object-oriented scripting language.
25. Choose the server-side JavaScript object?
A. FileUpLoad
B. Function
C. File
D. Date
26. Choose the client-side JavaScript object?
A. Database
B. Cursor
C. Client
D. FileUpLoad
27. Which of the following is not considered a JavaScript operator?
A. new
B. this
C. delete
D. typeof
28. ______method evaluates a string of JavaScript code in the context of the specified object.
A. Eval
B. ParseInt
C. ParseFloat
D. Efloat
29. Which of the following event fires when the form element loses the focus: <button>, <input>, <label>, <select>, <textarea>?
A. onfocus
B. onblur
C. onclick
D. ondblclick
30. The syntax of Eval is ________________
A. [objectName.]eval(numeric)
B. [objectName.]eval(string)
C. [EvalName.]eval(string)
D. [EvalName.]eval(numeric)
31. JavaScript is interpreted by _________
A. Client
B. Server
C. Object
D. None of the above
32. Using _______ statement is how you test for a specific condition.
A. Select
B. If
C. Switch
D. For
33. Which of the following is the structure of an if statement?
A. if (conditional expression is true) thenexecute this codeend if
B. if (conditional expression is true)execute this codeend if
C. if (conditional expression is true) {then execute this code>->}
D. if (conditional expression is true) then {execute this code}
34. How to create a Date object in JavaScript?
A. dateObjectName = new Date([parameters])
B. dateObjectName.new Date([parameters])
C. dateObjectName := new Date([parameters])
D. dateObjectName Date([parameters])
35. The _______ method of an Array object adds and/or removes elements from an array.
A. Reverse
B. Shift
C. Slice
D. Splice
36. To set up the window to capture all Click events, we use which of the following statement?
A. window.captureEvents(Event.CLICK);
B. window.handleEvents (Event.CLICK);
C. window.routeEvents(Event.CLICK );
D. window.raiseEvents(Event.CLICK );
37. Which tag(s) can handle mouse events in Netscape?
A. <IMG>
B. <A>
C. <BR>
D. None of the above
38. ____________ is the tainted property of a window object.
A. Pathname
B. Protocol
C. Defaultstatus
D. Host
39. To enable data tainting, the end user sets the _________ environment variable.
A. ENABLE_TAINT
B. MS_ENABLE_TAINT
C. NS_ENABLE_TAINT
D. ENABLE_TAINT_NS
40. In JavaScript, _________ is an object of the target language data type that encloses an object of the source language.
A. a wrapper
B. a link
C. a cursor
D. a form
41. When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type ___________
A. ScriptObject
B. JSObject
C. JavaObject
D. Jobject
42. _______ class provides an interface for invoking JavaScript methods and examining JavaScript properties.
A. ScriptObject
B. JSObject
C. JavaObject
D. Jobject
43. _________ is a wrapped Java array, accessed from within JavaScript code.
A. JavaArray
B. JavaClass
C. JavaObject
D. JavaPackage
44. A ________ object is a reference to one of the classes in a Java package, such as netscape.javascript .
A. JavaArray
B. JavaClass
C. JavaObject
D. JavaPackage
45. The JavaScript exception is available to the Java code as an instance of __________
A. netscape.javascript.JSObject
B. netscape.javascript.JSException
C. netscape.plugin.JSException
D. None of the above
46. To automatically open the console when a JavaScript error occurs which of the following is added to prefs.js?
A. user_pref(" javascript.console.open_on_error", false);
B. user_pref("javascript.console.open_error ", true);
C. user_pref("javascript.console.open_error ", false);
D. user_pref("javascript.console.open_on_error", true);
47. To open a dialog box each time an error occurs, which of the following is added to prefs.js?
A. user_pref("javascript.classic.error_alerts", true);
B. user_pref("javascript.classic.error_alerts ", false);
C. user_pref("javascript.console.open_on_error ", true);
D. user_pref("javascript.console.open_on_error ", false);
48. The syntax of a blur method in a button object is ______________
A. Blur()
B. Blur(contrast)
C. Blur(value)
D. Blur(depth)
49. The syntax of capture events method for document object is ______________
A. captureEvents()
B. captureEvents(args eventType)
C. captureEvents(eventType)
D. captureEvents(eventVal)
50. The syntax of close method for document object is ______________
A. Close(doc)
B. Close(object)
C. Close(val)
D. Close()
Posted in: Interview Questions asp.net | Tags: client-side ajax javascript top 50 jsobject wrapper ns_enable_taint javaarray javaclass blur web browser navigator livewireConfirm() Function in javascript
A CONFIRM box is used when you are trying to get a YES / NO answer from the visitor. The OK button acts as the YES response the CANCEL button acts as the NO response.
To get the CONFIRM actions to perform, we have to use a VARIABLE situation to control it. That means, we have to use a bit of algebra to temporarilly assign a value to the visitor's answer choice. After the value (answer) is determined, the script then carries out the set of instructions accordingly. This is usually done with an IF...ELSE statement. IF the answer is true, do this. ELSE the answer is false, so do this instead.
Examples
- JavaScript Confirm() - example of using a JavaScript confirm() method. Returns a boolean true or false.
Ex: <a href="javascript: confirm('When finished, click OK'); void('')">JavaScript Confirm()</a> - Results Example - Showing how to capture the results. Returns a boolean true or false.
Ex: <a href="javascript: alert('Your choice was: ' + confirm('When finished, click OK') ); void('')">Results Example</a> - If Example - Showing how to capture the results. Returns a boolean true or false.
Ex: <a href="javascript: if (confirm('Continue?')) { alert('You chose true') } else { alert('You chose false.') }; void('')"> - Confirm OK, then goto URL (uses onclick()) - Confirm, then next web page - If you press 'OK', then you will launch another web page.
Ex: <a href="ex_confirm_continuepressed.htm" onclick = "if (! confirm('Continue?')) return false;"> - Confirm OK, then popup a new window (uses onclick()) - Confirm, then next web page - If you press 'OK', then you will launch another web page.
Ex: <a href="ex_confirm_continuepressed.htm" onclick = "if (! confirm('Continue?')) return false;"> - Confirm OK, then goto a URL (uses window.location.href) - Confirm, then next web page - If you press 'OK', then you will launch another web page.
Ex: <a href="javascript: if (confirm('Continue?')) { window.location.href='ex_confirm_continuepressed.htm' } else { void('') }; "> - Confirm OK, then popup a new window (uses window.open()) - Confirm, then next web page - If you press 'OK', then you will launch another web page.
Ex: <a href="javascript: if (confirm('Continue?')) { window.open('ex_confirm_continuepressed.htm'); void('') } else { void('') }; "> - The normal html would look like:
blnAnswer = confirm('When finished, click OK')
Use a javascript confirm box to ask the user if they want to delete
Use a javascript confirm box to ask the user if they want to delete
<script>
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
</script>
<a href="javascript:confirmDelete('delete.page?id=1')">Delete</a>
Another way
<a href="delete.page?id=1" onclick="return confirm('Are you sure you want to delete?')">Delete</a>
Just a smart demo :)
Posted in: programming asp.net | Tags: javascript confirm demo