Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Remote Validation when JavaScript is disabled on browser.

  • In this article we are going to see what to do when JavaScript is disabled on client browser and Remote attribute does not validate the logic.
  • To understand this article better read Remote Validation article first, we have used same UserName validation scenario in this article.
Remote Validation

What’s wrong when JavaScript is disabled?
When JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code.

Why JavaScript disabled?
It depends on user to user whether they want JavaScript enable on browser or not. Following are the most common reason to disable JavaScript on browser.

Speed & Bandwidth
Usability & Accessibility
Platform Support
Security

Why Server side logic?
The server side logic is necessary as client side logic does not work due to any reason it is always safe and good to have server side logic.



Controller:
 
[HttpPost]
        public ActionResult Index(UserViewModel model)
        {
            RemoteValidationService service = new RemoteValidationService();
            if (service.IsValidUserName(model.UserName))
            {
                ModelState.AddModelError("UserName", "Username already exist");
                return View(model);
            }
            service.SaveUser(model);
            return View();
        }
    
The form is posted to the above Action method. In this method we are checking if username is present in database or not. If username is present in database then we are adding an error to ModelState making it invalid and returning the View with model having model error. So, this will show error message against the UserName control.

Screenshot:



So it is good practice to have server side validation as backup to client side validation. This is how you can cover up the validation performed by Remote attribute by writing server side logic as well.

Arrays in JQuery

  • The Array object is used to store multiple values in a single variable. 
  • An Array can hold different types of data types in a single array slot, which implies that an array can have a string, a number, or an object in a single slot.
Creating an Array:

An Array object can be created in the following ways:
  • Using the array Constructor
  • Using the array literal notation
Using the array Constructor
An empty array is created in cases where you do not know the exact number of elements to be inserted in an array. You can create an empty array by using an array constructor, as shown below:

    var myArray = new Array();

You can also create an array of any given size as shown below:


    var myArray = new Array(size);
    var myArray = new Array(20);

In the preceding code snippet, an array with 20 items is created.

You can also create an array with given elments as shown below:



    var array1 = new Array("Henry", "Fabregas", "Wilshere", "Cazorla", "Ozil");
    var array2 = new Array("IT", "Weekend", "Appraisal", "Escalation", "Resignation");

In the preceding code arrays with given values are created.

Using the array Literal notation

An array can be created by using the array literal notations. Array literal notations are comma-separated list of items enclosed by square brackets.

The syntax to create an empty array by using the array literal notation is shown below:



    var myArray = [];

The following code snippet shows how to create an array with given elements:


    var array1 = ["Ozil", "Cazorla"];
    var array2 = [6, "Cazorla",true];

In the preceding code snippet, an array containing different values, such as number 6, string Cazorla and boolean value true is created.

Methods of Array Object


  • push:
The push method adds new element as the last element and returns the length of the new array.

Simple Example:



In the above example, we have create a simple array, and added two elements to it. We have also created button on click of which the array elements are shown using paragraph element.

Another Example:





In the above example, we have created an array added elements into it as per user choice and also displayed its size.



  • pop: 
The pop method removes the last element of an array and returns that element. It is opposite to the method push.

Simple Example:


In the preceding example, we have created an array with five elements. We then used pop method to remove last element from an array. The pop method also returned the element removed, we have captured it in a variable and showed on UI.

Another Example:




In the preceding example, we have created an array. On click of pop button we are removing last element from the array and displaying the removed and current array.



  • concat:
The concat method joins two or more arrays and returns te joined array. The concat method accepts the another array object to concat. In order to concat more than two arrays, pass multiple arrays to concat method comma separated.



In the preceding example, we have shown how to concat two or more arrays using concat method.




  • join:
The join method joins all elements of an array into a string. This method creates a string representation of an array by joining all its elements using a separator string. If no separator is supplied, i.e. join() without an argument, the array will be joined using comma.



In the preceding example, we have seen how to join array elements by passing different arguments.



  • reverse:
The reverse method reverses the order of list of elements in an array.


In the preceding example, we have created an array used reverse method and displayed the result.


  • shift:
The shift method removes the first element from an array and returns the removed element. The combination of push() and shift() creates the method of queue.



In the preceding example, we have used shift method to remove the first element from an array.


  • slice:
The slice method selects part of an array and returns that selected part as a new array. The slice method takes one parameter which is the index of element to start slicing.







  • sort:
The sort method sorts the elements of an array. This method takes one parameter, which is a comparing function. If this function is not given, the array is sorted ascending.



In the preceding example, we have used sort method to sort the array elements in both ascending and descending order. In case of descending, If the return value is less than zero, the index of a is before b, and if it is greater than zero it's vice-versa. If the return value is zero, the element's index is equal.


  • splice:
The splice method adds or removes the elements of an array. The splice takes three parameters:


  • Index – The starting index.
  • Length – The number of elements to remove.
  • Values – The values to be inserted at the index position.




  • toString:
The toString method converts an array into a string and returns the string.





  • unshift:
The unshift method adds new elements to an array and returns the new length. The unshift element adds elment to the first position.





Length property of Array object
The length property holds the number of elements in an array. This property is used to determine the amount of items in an array.




Looping through an array

Following are the ways by which we can loop through an array.


Dynamic HTML Editor using HTML and Javascript



  1. In this article we will see how to create a Dynamic HTML Editor.
  2. This editor is created using HTML and Javascript.
  3. I have created frames to separate the region for typing and to show the result.
  4. We have used setTimeOut method to call a javascript method which picks whatever you write on left frame and updates on the right frame. The interval set to update the right frame is 150 milliseconds.

Code :


<html>
<head><title>Editor</title>
<script type="text/javascript">
    var structure = '<html>' +
'<head><title>Editor</title>' +
'<style type="text/css">' +
'.expand { width: 100%; height: 100%; background-color:black; color:white; font-family:comic sans ms; font-weight:bold; }' +
'.close { border: none;margin: 0px; padding: 0px; }' +
'.color{background-color:black; color:white;}' +
'html,body { overflow: hidden;}' +
'</style>' +
'</head>' +
'<body class="expand close">' +
'<form name="f" class="expand close">' +
'<textarea id="txtarea" wrap="hard" name="ta" class="expand close">' +
'</textarea>' +
'</form>' +
'</body>' +
'</html>';
    var headerText = '<html>' +
'<head><title>Header</title>' +
'<style type="text/css">' +
'#p1{font-family:comic sans ms; font-weight:bolder; font-size:30px; text-align:center; color:green}' +
'#p2{font-family:comic san ms; font-weight:bold; font-size:15px; text-align:center;color:green}' +
'</style>' +
'</head>' +
'<body bgcolor="silver">' +
'<p id="p1"><u>Dynamic Editor</u></p>' +
'<p id="p2">Edit And See</p>' +
'</body>' +
'</html>';

    var footerText = '<html>' +
'<body bgcolor="silver">' +
'</body>' +
'</html>';
    function init() {
        window.frame2.document.write(structure);
        window.frame2.document.close();
        window.frame1.document.write(headerText);
        window.frame4.document.write(footerText);
        update();
    }
    var old = "";
    function update() {
        var textarea = window.frame2.document.f.ta;
        var d = frame3.document;
        if (old != textarea.value) {
            old = textarea.value;
            d.open();
            d.write(old);
            d.close();
        }
        window.setTimeout(update, 150);
    }
</script>
</head>
<frameset rows="20%,*,20%" onload="init()">
<frame name="frame1" src="">
<frameset cols="50%,50%">
<frame name="frame2" src="">
<frame name="frame3" src="">
</frameset>
<frame name="frame4" src="">
</frameset>
</html>

The above code created a Dynamic HTML Editor. This editor gives you the dynamic feeling. The HTML code you write on left, immediately is updated on right frame. We can even write or use Javascript on this editor. This editor does not support jQuery.

Javascript csharp Alert box Code


Javascript csharp Alert box Code


  1. Open Alert.cs File which you have created inside the AppCode Folder.You can add the following piece of code in the Alert.cs file
  2. We need to show Alerts at various Events like incorrect username or password or compulsory fields are not provided during registration at that we can show an alert to user for this we have made this common class.It is a generic class and it can be used in any project and it can be called from any page without even creating the object as it is public static. 
  3. Both Alert Class and Show Method are Public and Static which makes them accessible without creating object in all files of project

Alert.cs C# Code:

using System.Web;
using System.Text;
using System.Web.UI;

/// 
/// A JavaScript alert
/// 
public static class Alert
{

  /// 
  /// Shows a client-side JavaScript alert in the browser.
  /// 
  /// The message to appear in the alert.
  public static void Show(string message)
  {
    // Cleans the message to allow single quotation marks
    string cleanMessage = message.Replace("'", "\\'");
    string script = "";

    // Gets the executing web page
    Page page = HttpContext.Current.CurrentHandler as Page;

    // Checks if the handler is a Page and that the script isn't allready on the Page
    if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
    {
      page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
    }
  }
 
}


    

Calling Alert Class from Csharp Code

   Alert.Show("Incorrect UserName/Password ");
   
Here we just have to pass the Message in the form of String and it will show the alert