X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

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

Thursday, September 10, 2015

AngularJS Routing Simple Example


Introduction to AngularJS Routing

AngularJS allows us to divide the page into multiple sections or views. So for redirecting between the views we use AngularJS Routing. These views can be bind to different controllers or same controller.

AngularJS Routing Patterns

Below are the sample route patterns in AngularJS if you are running the application in local machine -

http://localhost/index.html#electronics
http://localhost/index.html#furniture
http://localhost/index.html#books

As you can see all the urls have "#" sign, which is used to denote the view name. So our parent view name here is - "Index.html" and child view names are - "electronics", "furniture" and "books".

AngularJS Routing Library

Now lets create a sample e commerce AngularJS application for AngularJS Routing demo -
First lets create a module for our AngularJS application -

var myApp = angular.module('myApp', ['ngRoute']);

For routing to work we need to have module - 'ngRoute' so its added as dependency module above.
"$routeProvider" is also used for configuring the routes in AngularJS.

So for these routing configurations include library - "angular-route.js" -

<script src="scripts/angularJS/angular.min.js" type="text/javascript"></script>
<script src="scripts/angularJS/angular-route.js" type="text/javascript"></script>

AngularJS Routing Code

Below is the sample code for routing -

myApp.config(function ($routeProvider) {
 $routeProvider
    .when('/Electronics',
         {
          templateUrl: 'views/electronics.html',
          controller: 'catgrController'
         })
    .when('/Men',
        {
         templateUrl: 'views/men.html',
         controller: 'catgrController'
        })
    .when('/Women',
    {
     templateUrl: 'views/women.html',
     controller: 'catgrController'
    })
     .when('/Furniture',
    {
     templateUrl: 'views/furniture.html',
     controller: 'catgrController'
    })
  .when('/Books',
    {
     templateUrl: 'views/books.html',
     controller: 'catgrController'
    })
  .otherwise('/',
  {
   templateUrl: 'Index.html',
   controller: 'catgrController'
  });
});

The above code looks straightforward. Based on the url view has been displayed. Below is my HTML for routing -

<div class="page-content" ng-controller="hmcontroller">
<div class="row">
  <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
        <ul class="nav">
          <!-- Main menu -->
          <li><a href="#/Electronics" ng-click="getSelectedText('Electronics')"><i class="glyphicon glyphicon-home"></i> Electronics</a></li>
          <li><a href="#/Men" ng-click="getSelectedText('Men')"><i class="glyphicon glyphicon-edit"></i> Men</a></li>
          <li><a href="#/Women" ng-click="getSelectedText('Women')"><i class="glyphicon glyphicon-list"></i> Women</a></li>
          <li><a href="#/Furniture" ng-click="getSelectedText('Furniture')"><i class="glyphicon glyphicon-list"></i>Furniture</a></li>
          <li><a href="#/Books" ng-click="getSelectedText('Books')"><i class="glyphicon glyphicon-list"></i> Books</a></li>
        </ul>
    </div>
  </div>
  <div class="col-md-10">
    <div class="content-box-header panel-heading">
        <div class="panel-title">{{pageTitle}}</div>
    </div>
  <div class="row">
  <div class="col-md-12 panel-info">
      <div class="content-box-large box-with-header">
        <div ng-view></div>
      </div>
   </div>
 </div>
</div>
</div>
</div>

As you can see in the above code snippet menu options are in "<li>" tag. "hmcontroller" is my controller script, which is used for displaying the page name clicked.

hmcontroller.js -

myApp.controller('hmcontroller', ['$scope', function ($scope) {

 $scope.getSelectedText = function (selectedText) {
  $scope.pageTitle = selectedText;
 };

}]);

Below is the output -


Hope this post is useful. Please put your thoughts in the comment section below.






Monday, February 16, 2015

Using local storage in jquery

Introduction for using local storage in jquery
Local storage is basically used to store the information at client side i.e, within user browser. Local storage can accommodate more data unlike cookies and the data is secure too.

How localstorage is better than Cookies ?
Below are the pros of localstorage -

  • localstorage is supported by modern browsers out now.
  • localstorage can store nearly 5 MB of data where as cookies can only store 4 KB
  • localstorage data has not been sent in HTTP header unlike cookies.

Above only few pros have been listed since this post is on using the localstorage in our project.

How to use localstorage in my project ?

So i will use the same list of files as i have created in my earlier post. You can find that post here.

And my javascript file has been modified to introduce localstorage. So here i am going to store the value of "Category Name" field (created in previous post) in localstorage as you see below -

$(document).ready(function () {
 $("#saveCategory").click(function () {
  
  var categoryName = $("#CategoryName").val();

  localStorage.setItem('name', categoryName);

  if($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
});
In the above code "Category Name" field value is being stored in localstorage having key 'name'.

Now to display the value of localstorage (as alert box)  i will create a new action method as shown below and i change my post action method like this -

[HttpPost]
public ActionResult Index(Category catgr)
{
 return RedirectToAction("TestAction");
}

public ActionResult TestAction()
{
 ViewBag.Message = "Your test page.";
 return View("Test");
}
As you can see above new action method "Test Action" has been added and it is calling "Test.cshtml". So this page is just created to display the localstorage (in alert box).

So below is the code to display the value stored in localstorage -

<script type="text/javascript">

 var value = localStorage.getItem('name');

 alert(value);

 localStorage.removeItem('name');
</script>
So the above script is being added in "Test.cshtml". Make sure you remove the item added in the localstorage once its used because the value will be there till localstorage is being removed or cleared and it could cause some unexpected results.

Hope you enjoyed this article. Please put your comments below.




Saturday, February 14, 2015

Jquery validation plugin remove rules


Introduction of jquery validation plugin

This article is the continuation of my previous jquery validation plugin article Unlike my previous article "Jquery validation plugin rules" here i am trying to remove the data annotation validation dynamically from jquery validation plugin.

Approach for using jquery validation plugin rules

After solving the issues of validate method in my project (explained that issue in this jquery validation plugin post ) i have added the data annotation validations, created a models etc.

Now lets see how we can remove the validations dynamically using jquery validation plugin in my MVC project -

Lets create a new MVC Project from Web template.

First we will create a model which we are going to use across the project -

public class Category
{
 [Required]
 public int CategoryID { get; set; }
 [Required]
 public string CategoryName { get; set; }
}
As you can see in the above code snippet, "Category" model is added with properties - "CategoryID" and "CategoryName" which are required. So basically in page when the user does not enter these values then error message - "Please Enter Category ID or Please Enter Category Name" will be displayed.

Now lets create a controls for these fields -

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "frmCategory" }))

{

 <div class="row">

  <div>

   <label class="label_txt">@Html.LabelFor(m => m.CategoryID)</label>

   @Html.TextBoxFor(m => m.CategoryID)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.CategoryID)

  </div>

 </div>



 <div class="row">

  <div>

   <label class="label_txt">@Html.LabelFor(m => m.CategoryName)</label>

   @Html.TextBoxFor(m => m.CategoryName)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.CategoryName)

  </div>

 </div>



 <input type="button" class="saveCategory" value="Save" id="saveCategory" />

}

As you can see above, I am using  type="button" and not type="submit" because in the click event of the button control i will submit the form using jquery. Below is the complete code of Jquery file -

$(document).ready(function () {
 
 $("#saveCategory").click(function () {
  
  if ($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
 
});
As you see in the above code we are just validating the form controls. As we discussed earliar, if the user has not entered the value in any of the textboxes, required error will be thrown. So after executing the above code we will get error like this in the screenshot -

Jquery validation plugin remove rules

Now we will try to remove the validation for "Category Name" field and if we enter the value in field "Category ID" the form becomes valid. Let us change the code to remove the validation for "Categoty Name" -

$(document).ready(function () {

 $("#saveCategory").click(function () {

  $("#CategoryName").rules("remove");

  if ($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
 
});
So after adding this code validation for "Category Name" field will be disabled. See the below screenshot of the screen as how it looks when "Save" button is clicked -
Jquery validation plugin remove rules

Once enter value for "Category ID" field, the form will be valid and it submits the form and below is the screenshot of post method, which is called after form submit -

Jquery validation plugin remove rules

So null value will be passed to "Category Name" field and the entered value - 5 goes to "Category ID" field.

I hope this article has helped you guys. Please comment your thoughts below.

typeerror $(...).validate is not a function jquery


Problem
In my project i have _Layout.cshtml and Index.cshtml and my javascript files. In my javascript file i am trying to use validate() method of Jquery plugin as i want to validate the form before submit. When i run my project i was getting error –
$(…).validate is not a function
Solution 1
If you are using validate() method of Jquery plugin then we have to make sure the library – “jquery.validate.min.js”  is being added. So even after adding this library in my Index.cshtml page issue has not yet been solved.  – Still an Issue
Solution 2
Added “jquery.validate.min.js” library in my _Layout.cshtml (master page) after registering the Jquery bundles. So we have to make sure “jquery.validate.min.js” library should be added after main Jquery library. So the sequence should be like below –

jquery-1.7.1.min.js
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

typeerror $(...).validate is not a function jquery
Make sure you are following the above sequence because of one library dependent on other. And make sure you have enabled the client side validation in web.config like below –

 
<appSettings>

 <add key=”webpages:Version” value=”3.0.0.0″ />

 <add key=”webpages:Enabled” value=”false” />

 <add key=”ClientValidationEnabled” value=”true” />

 <add key=”UnobtrusiveJavaScriptEnabled” value=”true” />

</appSettings>

Adding in _Layout.cshtml under <body> tag like below has solved the validate() method issue –

@Scripts.Render(“~/bundles/jquery”)
@Scripts.Render(“~/bundles/bootstrap”)
@RenderSection(“scripts”, required: false)


<script src=”~/MyFolder/jquery.validate.min.js” type=”text/javascript”/>
<script src=”~/MyFolder/jquery.validate.unobtrusive.min.js” type=”text/javascript”/>

<!-- Your other javascript libraries -->

Hope this article has solved your issue also. Please comment below.


Sunday, February 8, 2015

Jquery form submit confirm dialog

Introduction of Jquery form submit confirm dialog

Consider a scenario where we need to post the values of ASP.NET MVC Form on click of "Yes" button in confirm dialog. There are many questions raised in different forums on this topic so i thought lets discuss this today. Here i will try to explain how we can do it with easy steps. 

Approach for Jquery form submit confirm dialog

First step would be to create a class called "Customer.cs"  and using this as our model to our view.
 
public class Customer
{
 public string Fname { get; set; }
 public string Lname { get; set; }
 public string Address { get; set; }
}

Jquery form submit confirm dialog
I will use the existing "HomeController.cs" file for this example so lets change the content of "index.cshtml" view to incorporate customer model changes. Below is the sample of ASP.NET MVC Form -


@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { Id = "frmCustomer" }))
{

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Fname)

   @Html.TextBoxFor(m => m.Fname)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Fname)

  </div>

 </div>

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Lname)

   @Html.TextBoxFor(m => m.Lname)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Lname)

  </div>

 </div>

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Address)

   @Html.TextBoxFor(m => m.Address)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Address)

  </div>

 </div>

 <div class="align_left_tabs">

  <input type="button" value="Save" name="Save" id="SaveCustomer" />

 </div>
}

As you can see in the above code snippet of ASP.NET MVC Form, properties  - "Fname", "Lname" and "Address" are all input fields. So once the user enters the data into these text boxes and clicks the "Save" button, Pop up (Confirm Dialog) will appear and it gives user a option either "Save" or "Cancel". So Pop up content will be obtained from partial view. So we are creating an action method to load the pop up. 

Below is the code snippet for these functionalities -

First is loading the partial view on click on "Save" button 
 
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script type="text/javascript">

 var WarningURL = '@Url.Action("WarningPopUp", "Home")';

 $(document).ready(function () { 

  $("#SaveCustomer").click(function () {

   showWarningPopup();

  });


  function showWarningPopup() {

   var $confirm = $("<div id='divWarning'></div>");

   $confirm.empty();

   $confirm.dialog({

    autoOpen: false,

    title: 'Message',

    width: 400,

    draggable: false,

    resizable: false,

    closeOnEscape: false,

    dialogClass: 'no-close',

    modal: true,

    height: 150,

    cache: false,

    open: function (event, ui) {

     $confirm.load(WarningURL);

    }

   });

   $confirm.dialog("open");

   return false;

  }

 });

</script>

As you can see above function - "showWarningPopup" is used to display a pop up (confirm dialog) and "WarningURL" variable is pointing to the action - "WarningPopUp", which is in "Home" controller. 

Action method -
 
public ActionResult WarningPopUp(string name)
{
 return PartialView("_WarningPopup", name);
}

Pop up/ Confirm Dialog code -


<script type="text/javascript">

 function destroyPopup() {

  $('#divWarning').dialog('destroy').remove();

 }

 function postCredentials() {

  $("#frmCustomer").submit();

 }

</script>

<div id="timeOutPopup" class="row_shift20">

 <div style="margin-bottom:50px">Please Confirm Details</div>

 <ul>

  <li class="popUpCancelBtnWidth"><input type="button" value="Cancel" onclick="destroyPopup()" /></li>

  <li class="popUpConfrmBtnWidth"><input type="button" value="Save" onclick="postCredentials();" class="green_input" /></li>

 </ul>
</div>
The above method is quite straight forward. As we discussed on click of "Save" button javascript function - "postCredentials" which submits the parent form (which has user entered values). After putting breakpoint in the post method it looked like this -

Jquery form submit confirm dialog

Hope you enjoyed this article of ASP.NET MVC Form even though it is long. Please comment your thoughts below.

Wednesday, December 17, 2014

jquery validation - Client side validation using jquery in asp.net mvc

Introduction for "client side validation using jquery in asp.net mvc"

In most of the cases we are going to use Data Annotations for validation in MVC. Let's not forget the point of unobtrusive client-side validation which turned out to be a boon for the developers. In unobtrusive client-side validation, validation rules are defined using attributes added to the generated HTML elements. This article will focus on adding the validation rules from client side.

client side validation using jquery in asp.net mvc
Let's get started

Now let's dive into the code part as how we can add the rules for the controls. Before that i need to discuss when we can use this type of approach – Consider a scenario where you are re-using the page with hide and show the controls of the page, eg : if one client wants textbox and another client wants dropdownlist for the same field in a same page and if the validation rules are different for both these controls then adding the rules from client side would be a better approach.

For enabling client side validation, we required to include following scripts in our view or layout page in the following order.

<script src="~/Scripts/jquery-{version}.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Now lets create a new project for this and lets add the controller, models, views and javascript for our project.

  1. Create a new MVC project 
  2. Add a new controller called "ProductController"
  3. Add a new model called "ProductModel" and add the properties - Name, Description and Amount
  4. Add a new view called "Index.html" for our product
  5. Add a new javascript file for validation "productvalidation.js"

Now we will just set the validation rules for all the properties in the ProductModel in productvalidation.js file. Script for adding the validation rules for our controls in a page -

$(document).ready(function () {

    var regexAlpabetsOnly = /^[a-zA-Z\- ']*$/;
    var regexNumbersOnly = /^\d+$/;
   
    $('#Name').rules("add", {
       required: true,
       minlength: 2,
       messages: {
         required: "Please enter name",
         minlength: "At least 2 characters are mandatory"
       }
   });

   $('#Description').rules("add", {
      required: true,
      regex: regexAlpabetsOnly,
      maxlength : 20,
      messages: {
        required: "Please enter description",
        regex: "Please enter alphabets in description field",
        maxlength: "Exceeded maximum length of description"
      }
  });

   $('#Amount').rules("add", {
      required: true,
      regex: regexNumbersOnly,
      messages: {
        required: "Please enter Amount",
        regex: "Please enter numbers in amount field"
      }
   });

 });

As you see above nothing fancy all are straight forward and we have following validations -

  • For "Name" property we are adding required field validation and minimum length validation.
  • For "Description" property we are adding required field validation and regex validation to allow only alphabets.
  • For "Amount" property we are adding required field validation and regex validation to allow only numbers.

All are fine but only concern here is error messages are hardcoded. So its always a better idea to get these texts from resource file instead of hardcoding.

Now lets add the resource file and move these texts into resource file. For brevity i have not given the lump steps here -

Once its added the next would be to get the resource file data to javascript and that again is easy. Better option to do this is serialize the resource file and pass the JSON object to javascript.

Lets do that now -

In Controller lets add a method which will return JSON object -

[HttpGet]
public JavaScriptResult GetResourceFileData()
{
 return ResourceSerialiser.GetResourceSerailizedData(Resource.ResourceManager);
} 

For Serializing the resource file data -
 
public static JavaScriptResult GetResourceSerailizedData(ResourceManager resourceManager)
  {
     string cacheName = string.Format
       ("ResourceJavaScripter.{0}", CultureInfo.CurrentCulture.Name);

     JavaScriptResult value = HttpRuntime.Cache.Get(cacheName) as JavaScriptResult;

     if (value == null)
     {
        JavaScriptResult javaScriptResult = CreateResourceJSON(resourceManager);
        HttpContext.Current.Cache.Insert(cacheName, javaScriptResult);
        return javaScriptResult;
     }

      return value;
  }

  static JavaScriptResult CreateResourceJSON(ResourceManager resourceManager)
  {
       ResourceSet defaultSet = resourceManager.GetResourceSet
             (CultureInfo.GetCultureInfo("en"), true, true);
       ResourceSet resourceSet = resourceManager.GetResourceSet
             (CultureInfo.CurrentCulture, true, true);

       var resourceBaseName = resourceManager.BaseName;
       var jsonObjectName = resourceBaseName.Substring(resourceBaseName.LastIndexOf(".") + 1);

       StringBuilder sb = new StringBuilder();
       sb.Append("[");
       sb.Append("{");

       foreach (DictionaryEntry dictionaryEntry in resourceSet)
            if (dictionaryEntry.Value is string)
           {
                string value = resourceSet.GetString
                    ((string)dictionaryEntry.Key) ?? (string)dictionaryEntry.Value;
                sb.AppendFormat("\"{0}\":\"{1}\"", dictionaryEntry.Key, Encode(value));
                sb.Append(",");
           }


        string script = sb.ToString();
        if (!string.IsNullOrEmpty(script)) 
             script = script.Remove(script.Length - 1);


        script += "}]";
   

        JavaScriptResult result = new JavaScriptResult { Script = script };
        return result;
    } 

    static string Encode(string val)
    {
         val = (val).Replace("\"", "\\\"").Replace('{', '[').Replace('}', ']');
         val = val.Trim();
         val = System.Text.RegularExpressions.Regex.Replace(val, @"\s", " ");
         return val;
    }

In javascript lets add a new AJAX call to get the JSON object from controller method -

$.ajax({
  cache: false,
  type: "GET",
  url: "Product/GlobalResourceFileData",
  async: false, 
  dataType: "json",
  success: function (resourceData) {
   resourceFilevalues = resourceData[0];
  }
 });

" resourceFilevalues " is global variable which is used to receive the JSON object in AJAX call given above.

Now the hardcoded values will be replaced by the resource file properties like below -

$('#Name').rules("add", {
  required: true,
  minlength: 2,
  messages: {
   required: resourceFilevalues.NameRequiredErrMessage,
   minlength: resourceFilevalues.NameMinLengthErrMessage
  }
 });

 $('#Description').rules("add", {
  required: true,
  regex: regexAlpabetsOnly,
  maxlength : 20,
  messages: {
   required: resourceFilevalues.DescriptionRequiredErrMessage,
   regex: resourceFilevalues.DescriptionRegexErrMessage,
   maxlength: resourceFilevalues.DescriptionMaxLengthErrMessage
  }
 });

 $('#Amount').rules("add", {
  required: true,
  regex: regexNumbersOnly,
  messages: {
   required: resourceFilevalues.AmountRequiredErrMessage,
   regex: resourceFilevalues.AmountRegexErrMessage
  }
 });

So hope this article is useful and i agree this is the longest post i have written :-)

Monday, December 1, 2014

Invalid range in character set javascript error

Invalid range in character set javascript error

I faced this issue when i was working on IE 8 and this issue has driven me crazy.Since this is not a straight forward issue to fix, i tried to narrow down the problem and finally came to know the regular expression what i used for validation is the culprit for this.This issue would not have come if you are running your application in the high end browsers.

The line which was causing the problem -
var SpecialCharRegex = /^[0-9a-zA-Z',-\s]*$/;
After doing lot of googling i found the issue and the issue is "-" in this regular expression.This error is due to the hyphen, which is mistakenly being used to represent a range and is not properly escaped. To fix this lets add backslash before "-" and change the regular expression like this -
var SpecialCharRegex = /^[0-9a-zA-Z',\-\s]*$/;
Simple logic is either put "-" at the beginning or end of the character class or use backslash to do a regex escape.
It works like a charm !!