Showing posts with label HTML5. Show all posts
Showing posts with label HTML5. Show all posts

Thursday, June 13, 2013

How hash-based/pushState navigation works

 
For hash-based navigation, the visitor's position in a virtual navigation space is stored in the URL hash, which is the part of the URL after a 'hash' symbol (e.g.,/my/app/#category=shoes&page=4). Whenever the URL hash changes, the browser doesn't issue an HTTP request to fetch a new page; instead it merely adds the new URL to its back/forward history list and exposes the updated URL hash to scripts running in the page. The script notices the new URL hash and dynamically updates the UI to display the corresponding item (e.g., page 4 of the "shoes" category).

This makes it possible to support back/forward button navigation in a single page application (e.g., pressing 'back' moves to the previous URL hash), and effectively makes virtual locations bookmarkable and shareable.

PushState is an HTML5 API that offers a different way to change the current URL, and thereby insert new back/forward history entries, without triggering a page load. This differs from hash-based navigation in that you're not limited to updating the hash fragment — you can update the entire URL.

Sunday, June 2, 2013

How to Use Master Pages in ASP.NET MVC 3 / MVC 4

 
In MVC 3 and upwards, with the new Razor view engine you will no longer see the master page is used in default project with an account controller that uses forms authentication.

It still have the concept of master pages through _Layout.cshtml file with Razor support. Check the Shared folder in your project and you'll find the _Layout.cshtml which is used as the master page.


Tuesday, April 9, 2013

What is web storage in HTML5?

 
The term web storage refers to HTML5’s client-side data-storage mechanism. Web storage allows you to store data on the client side as key-value pairs. The W3C recommended a web storage size limit of 5MB per origin (see the section “Security Considerations for Web Storage” to learn more about origins). However, individual browsers may slightly deviate from this limit. For example, IE8 allows web storage of up to 10MB.

Although both web storage and cookies store data on the client side, they work differently. Cookies are passed between client and server with each and every request from a given web site. On the other hand,
web storage is never passed to the server automatically. If you need to transmit data from web storage to
the server-side code, you must resort to a programmatic approach such as jQuery calling server-side code
or a hidden form field. Additionally, unlike cookies, you can’t set an expiration time for web storage. You
either need to write code to delete stale items or count on the user to delete the stale items using an option
in the browser.

Web storage comes in two flavors: session storage and local storage. These two types are exposed as sessionStorage and localStorage attributes of the window object, respectively. As you might have guessed,
session storage is persisted as long as the current browser (or its tab) instance is running. The moment you
close the browser instance (or tab), the data is removed. If you load the web site again later, it can’t accessany of the previously stored data. Session storage is suitable for a single transaction. Local storage, unlike session storage, stores data across multiple instances of the browser and also beyond the current session. In summary, web storage is good choice if

• You need to store data exceeding the size limits of cookie-based storage.
• You don’t need to pass data to and from the server with every request.
• You don’t need to set any specific expiration time for the data.

However, web storage may not be a good choice if

• You wish to store a huge amount of data.
• Your data can’t be easily stored as key-value pairs (binary data or BLOBS, for example).
• Data to be stored is sensitive.

Sunday, April 7, 2013

Enabling Spell-Check in HTML Form

 

In HTML5 we can use spellcheck attribute in textarea HTML element to enable the spell check ability. By setting it to true it'll enable the spell check ability and setting it to false will disable the spell check ability.

<textarea id="textarea1" rows="5" cols="50" spellcheck="true"></textarea>




Friday, April 5, 2013

Date Time Picker in HTML5

 
In ASP.NET Web Forms, the Calendar server control lets you pick dates. However, the biggest downside of Calendar is that it requires a post back when a date is selected. No wonder ASP.NET developers often used JavaScript-based pop-up date-time pickers in their web applications. It would be better if the browser itself could display a datetime picker, and that’s where the date and time input types come into the picture. Using these input types, you can select a date, a time, or both. The user can also select a complete week or month rather than a specific day or time.

■ Note As of this writing, Opera is the only browser that displays a pop-up date-time picker for the date and time input types. Chrome displays a pop-up date picker only when the input type is date; it renders a plain text box for other date and time types. Also, there is a difference in the display format for date. Opera, for example, displays dates in yyyy-MM-dd format, whereas Chrome displays them as per machine date format.
<input id="dt1" type="date" />
<input id="dt2" type="time" />
<input id="dt3" type="datetime" />
<input id="dt4" type="datetime-local" />
<input id="dt5" type="week" />
<input id="dt6" type="month" />

The six date-time input types allow you to accept date, time, date and time, local date and time, week, and month, respectively. The dates are displayed in yyyy-MM-dd format, whereas times are displayed in hh:mm:ss format. For weeks and months, the format is yyyy-Www and yyyy-MM, respectively. Below image shows how Opera displays these date-time input types.





Range Selector in HTML5

 


At times, you need to select (rather than enter) values falling within a specific range. Recollect the custom video player you developed in Chapter 3: you provided the facility to change the player’s volume. In such
cases it isn’t appropriate to expect the user to enter a volume level. Instead, it’s better to let them select a
volume level from a range. The following markup shows how you can use the range input type:

<input id="range1" type="range" min="1" max="5" step="1" />

Attributes such as min, max, and step have the same significance as for the number input type (min and max control the control’s minimum and maximum allowed values, and step controls the jump in the value).

Thursday, April 4, 2013

E-mail Validation in HTML5



E-mail addresses are commonly used on web sites for variety of reasons ranging from user registrations to
contact forms. You can accept e-mail addresses using the email input type.

<span>Enter your email address :</span>
<br />
<input id="email" type="email" />
<br />
<input type="submit" value="Submit"/>


As you can see, the type attribute is set to email. If you try to enter an invalid e-mail address, the browser displays an error message.

Notice that the error message is displayed only if the text box contains a value. If the text box is left empty, no validation is performed. This behavior is similar to ASP.NET validation controls.

Monday, April 1, 2013

Open .pdf inside a DIV tag

 
You can use HTML5 object element for opening a pdf document inside a div element. Below is a sample code.

<div id="target">
<object data="PDF/File_16.pdf" type="application/pdf" width="100%" height="700">
alt : <a href="PDF/File_16.pdf">test.pdf</a>
</object>
</div>

Friday, March 29, 2013

Embedding Silverlight Video Files in HTML5

Microsoft’s solution to displaying media files in a web page is Silverlight. Silverlight is seen as a competitor to Flash, but because it’s a relatively recent invention, it lags behind Flash in terms of popularity and widespread use. However, Silverlight is a flexible and powerful platform that can be programmed using .NET tools such as Visual Studio and Visual C#. You can also encode existing media files into a Silverlight specific format using Expression Web.

<object data="data:application/x-silverlight-2"
type="application/x-silverlight-2" width="300" height="300">
<param name="source" value="silverlightvideos/CleanTemplate.xap"/>
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50401.0" />
<param name="autoUpgrade" value="true" />
<param name="enableHtmlAccess" value="true" />
<param name="enableGPUAcceleration" value="true" />
<param name="initparams" value='playerSettings =<Playlist>
<DisplayTimeCode>false</DisplayTimeCode>
<EnableCachedComposition>true</EnableCachedComposition>
<EnableCaptions>true</EnableCaptions>
<EnableOffline>true</EnableOffline>
<EnablePopOut>true</EnablePopOut>
<StartMuted>false</StartMuted>
<StartWithPlaylistShowing>false</StartWithPlaylistShowing>
<StretchNonSquarePixels>NoStretch</StretchNonSquarePixels>
<Items>
<PlaylistItem>
<AudioCodec>WmaProfessional</AudioCodec>
<Description></Description>
<FileSize>1349539</FileSize>
<FrameRate>25</FrameRate>
<Height>360</Height>
<IsAdaptiveStreaming>false</IsAdaptiveStreaming>
<MediaSource>silverlightvideos/Video2.wmv</MediaSource>
<ThumbSource></ThumbSource>
<VideoCodec>VC1</VideoCodec>
<Width>640</Width>
</PlaylistItem>
</Items>
</Playlist>'/>
<a href="http://go2.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go2.microsoft.com/fwlink/?LinkId=108181"
alt="Get Microsoft Silverlight" style="border-style: none;"/>
</a>
</object>

Notice how the <object> tag now includes many pieces of information. The <param> and <Playlist> elements supply a great deal of data such as the path of the Silverlight compressed output file (.xap) and the configuration of the video being played.

Embedding Audio Files in HTML5

 
To embed an audio file into a web page, you can use an <object> tag.

<body>
<h2>Play Audio File</h2>
<object data="Media/Song.mp3" />
</body>


The data attribute of the <object> tag points to an MP3 audio file residing in the Media folder.

Embedding Flash Video Files in HTML5

 
Adobe Flash is one of the most popular ways of embedding video files in web pages. Due to its popularity,
all the leading browsers support the Flash plug-in. You can use the <object> tag to embed Flash videos in a
web page.

<object id="flash1" data="Media/Video1.swf" type="application/x-shockwave-flash" height="200" width="200"> 
<param name="movie" value="Media/Video1.swf"> 
</object> 

 The <object> tag this time plays a Flash video file Video1.swf. The type attribute specifies the MIME type for Flash videos (application/x-shockwave-flash).

Tuesday, March 26, 2013

Make the CheckBox a Required Field using jQuery



HTML:

<div class="smallDiv">
<h2>Check Atleast One CheckBox before submitting the Form</h2>
<asp:CheckBox ID="cb1" runat="server" Text="Option One" /><br />
<asp:CheckBox ID="cb2" runat="server" Text="Option Two" /><br />
<asp:CheckBox ID="cb3" runat="server" Text="Option Three" />
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
ToolTip="Select atleast one checkbox before clicking" />
<br /><br />
Tip: If the user has checked atleast one checkbox, and clicks the
Submit button, a postback occurs, otherwise the user is prevented
from submitting the form.
</div>

Jquery Script:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function () {
$('input[id$=btnSubmit]').click(function () {
var checked = $(':CheckBox:checked').length;
if (checked == 0) {
alert('Atleast one checkbox should be selected!');
e.preventDefault();
}
else {
alert('postback occured!');
}
});
});
</script>

Sunday, March 24, 2013

Using the jQuery $.ajax() Method in a Web Forms Application

The WCF service that converts temperature values between Celsius and Fahrenheit is shown below.

namespace AjaxWebForm
{
[DataContract]
public class TemperatureData
{

[DataMember]
public decimal Value { get; set; }
[DataMember]
public string Unit { get; set; }

}

[ServiceContract]

public interface IService
{
[OperationContract]

[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TemperatureData Convert(TemperatureData t);
}

public class Service : IService
{
public TemperatureData Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}

else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}

return t;
}
}
}

The TemperatureData class represents the data contract of the WCF service and contains two data member properties: Value and Unit. The IService interface represents a service contract for the service and defines a single method Convert(). The Convert() method accepts a TemperatureData object and returns a TemperatureData object after converting the temperature value to the other scale.

Notice that Convert() is decorated with an [WebInvoke] attribute. Due to this attribute, Convert() becomes callable from the client-side jQuery code. The RequestFormat and ResponseFormat properties of the [WebInvoke] attribute specify JSON as the communication format during request and response, espectively. The Method property specifies that Convert() can be invoked by HTTP POST requests. The Service class implements Convert(). The Convert() method checks the Unit of the incoming TemperatureData object and, depending on the Unit, converts the Value to the other scale.

The Service class’s Convert() method can be called using jQuery’s $.ajax() function as shown below
Using $.ajax() to Call the WCF Service Convert() Method

$(document).ready(function () {
$("#Button1").click(function () {
url = "Service.svc/Convert";
data = '{"Value":"' + $("#Text1").val() + '","Unit":"' + $("#Select1").val() + '"}';
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});

The Convert button’s click event handler contains the jQuery code for invoking the Convert() method. The $.ajax() function has many configurable settings. The url setting allows you to specify the remote resource URL. For a WCF service, the URL takes the form <path_to_svc_file>/<method_name>.

The type option lets you specify the HTTP request type to be used while making the request. The Convert() method is configured with the [WebInvoke] attribute to use a POST method, and hence type is POST. The data setting indicates the data to be sent to the server (if any) while making the call. Notice how data is captured in JSON format. A JSON object takes the form of key-value pairs: a key and its value are separated by a colon (:), and multiple key-value pairs are delimited by a comma (,).

The dataType setting governs the data type of the response (XML, JSON, and so on). Recollect that the [WebMethod] attribute specified ResponseFormat as JSON, so dataType here must be set to JSON to correctly process the data coming from the server.

If Convert() returns successfully, the function specified by the success option (OnSuccess) is called. If there is any error while calling the WCF service, a function specified by the error option (OnError) is called. The OnSuccess() function is where you process the data returned from the WCF service. OnSuccess() receives the return value of Convert() (the TemperatureData object) as a parameter. You can access its Value and Unit properties and display an alert box to the user.

In the OnError() function, you typically flag the error to the user or take some corrective action. OnError() receives an error object; you can display its status and statusText properties to the user. Figure shows a sample run of the Web Forms application.



Friday, March 22, 2013

Modifying the DOM Using jQuery

JQuery also lets you insert, append, remove, and replace elements from the HTML DOM so you can modify the document structure. For example, suppose you’re calling a remote service from client-side jQuery code and, based on what the service returns, you need to generate HTML markup on the fly. Such tasks can be accomplished using jQuery methods that let you manipulate the HTML DOM.

after()  - Inserts content after a specific element
append()  - Appends content as specified by the parameter to the end of the matched elements.
appendTo()  -  Appends the matched elements to the end of a target element.
attr()  -  Gets or sets an attribute value
before()  -  Inserts content before a specific element
clone()  -  Makes a deep copy of an element and its contents
empty()  -  Removes all the child nodes of a specific element
html()  -  Returns the HTML markup of an element
insertAfter()  -  Inserts content after a specific element
insertBefore()  -  Inserts content before a specific element
prepend()  -  Inserts content as specified by the parameter at the beginning of the matched elements
prependTo()  -  Inserts the matched elements at the beginning of a target element
remove()  -  Removes a specific element and all its child elements
removeAttr()  -  Removes an attribute from an element
replaceWith()  -  Replaces target element with specific content
text()  -  Returns the text content of an element including all child elements
val()  -  Returns the value from a form element
wrap()  -  Wraps every element of a matched set in a given element

Some Examples:
$("#container").append("<div>Hello</div>");
$("<div>Hello</div>").appendTo("#container");
$("span").replaceWith("<div class='class1'>Hello Universe!</div>");
$("<div class='class2'>Hello World!</div>").replaceAll("div.class1");

The first line of code from Listing adds <div>Hello</div> at the end of the container element. So, if the container is a <span> element, then after calling the append() method, the effective markup is <span id='container'><div>Hello</div></span>.

The second line of code uses the appendTo() method. This method is similar to the append() method with one difference: append() is invoked on the target element and accepts markup to be appended. The appendTo() method accepts a target element as a parameter and appends the specified markup at the end of the target.

The example of the replaceWith() method replaces all the <span> elements with <div class='class1'> elements. For example, if the original markup is <span>Hello World!</span>, then after calling the replaceWith() method, the new markup is <div class='class1'>Hello Universe!</div>.

Finally, the replaceAll() method replaces all the <div> elements with the CSS class class1 with <div>Hello World!</div>.

HTML5 and Browser Support

 
All the leading browsers—Mozilla Firefox, Google Chrome, Opera Software’s Opera, Apple Safari, and Microsoft IE—support HTML5 in varying degrees. These days, most browsers release updated versions frequently, and HTML5 support improves in each new version. IE is lagging slightly behind as far as the frequency of new releases is concerned, but IE9 does support several HTML5 features.

As a good programming practice, you should always test your Web Forms, views, and plain HTML pages in the browser you’re targeting. There are two ways to check whether the target browser supports a specific HTML5 feature:

• Statically at development time
• Dynamically at runtime

Checking for HTML5 Support Statically
With this approach, you manually ensure that the features used in your web pages are supported by your
target browser. You can get help from any of the online utilities that tell you whether a specific browser
version supports certain HTML5 features. Consider, for example, http://html5test.com, which provides a
nice way to detect browser support for HTML5. Figure 1-6 shows the home page of the HTML5 test site
displaying the HTML5 support score for the browser being used to view the site.