X

Subscribe To Our Mailing List

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

Friday, October 23, 2015

Child action only in MVC


Introduction

The public methods in the controller class can be called as action. So the actions can be invoked through the URL. But the child actions cannot be directly accessed through the URL instead it will be called from the view.


How to Use

Suppose we have to display the same information across couple of pages /views then we can create a partial view and this partial view can be used in those views.

Child Actions cannot be accessed through the URL. It should be called from the parent view. From the parent view we can use -

@Html.Action("ChildActionMethod", "ControllerName")

Or we can call the child action methods like this -

@{ Html.RenderAction("ChildActionMethod", "ControllerName"); }

And my child action methods should be decorated with the attribute - "ChildActionOnly" - which signifies the action can be called only as a child.

Below is my sample child action method -

[ChildActionOnly]
public ActionResult ChildActionMethod()
{
    return PartialView();
}

So as mentioned above, this child action can be called from -

@Html.Action -> Returns the action result as HTML String.  

@Html.RenderAction -> Renders the action result directly into the view.  

And as you can observe my child action is returning the partial view. Its not mandatory for child action to return the partial view always but its a good practice to return the partial view over view.

If you are accessing the child action method through URL you will get a error like -



Hope it helps. Please comment your thoughts below.





Friday, October 9, 2015

AngularJS Grid Example


Introduction

In this article i will try to show the sample grid in AngularJS and adding the button in each row to get the selected row details. I will use the same sample Web API service created in my previous article.


Practical Approach

Below is the screenshot of the sample project created -



Now lets move on to each file in the project -

<!doctype html>
<html>

<head>
<title> Grid Example </title>

</head>

<body ng-app="myApp">
   <div class="page-content">
   <div class="row">
    <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
     <ul class="nav">
      <!-- Main menu -->
       <li>
         <a href="#/GridExample" <i class="glyphicon glyphicon-home"></i> Grid Example</a>
       </li>
      </ul>
    </div>
     </div>
     
   <div class="col-md-10">
      <div class="content-box-header panel-heading">
     <div class="panel-title">Sample Grid Example</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>

<!-- Libaries for Bootstrap for controls -->
<!--Starts Here-->
<link href="scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="scripts/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/bootstrap/js/bootstrap.min.js"></script>
<!--Ends Here-->

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

<link href="css/styles.css" rel="stylesheet" />
<link href="content/ui-grid/ui-grid-unstable.css" rel="stylesheet" />
<link href="content/css/custom.css" rel="stylesheet" />

<script type="text/javascript" src="scripts/ui-grid-unstable.js"></script>

<script src="app.js"></script>
<script src="config.js"></script>

<script src="services/sampleService.js"></script>
<script src="controllers/sampleController.js"></script>

</body>
</html>

Above "index.html" has the references for controllers, services and stylesheet files. Library - "ui-grid-unstable.js" is used for loading the grid and it has functions required by the grid and stylesheet file also highlighted above.

If you checked my article it has all these files created already but in this example i will modify the controller part but service will be untouched.

So controller code for loading the grid -

myApp.controller('sampleCtrl', ['$scope', '$http', 'sampleService', function ($scope, $http, sampleService) {
 var products = sampleService.getProducts();

 products.then(function (response) {
  $scope.gridOptions = {
   data: response.data
  };
 });

 $scope.getProdName = function (row) {
  alert(row.entity.ProductName);
 };

 $scope.gridOptions = {
  enableFiltering: false,
  enablePaging: true,
  onRegisterApi: function (gridApi) {
   $scope.gridApi = gridApi;
  },
  columnDefs: [
    { name: 'Product Id', field: 'ProductId', width: 150 },
    { name: 'Product Name', field: 'ProductName' },
    {
     name: 'Details',
     cellTemplate: '<button class="btn btn-info btn-xs" 
                          ng-click="grid.appScope.getProdName(row)">View Product Name</button>',
                 enableFiltering: false,
                 enableSorting: false
       }
   ]
};

}]);


As shown above button control is added in "cellTemplate" section and on click of the button, product name value of the respective row will be popped up using function - "getProdName()".

For grid to work we should add the dependency while registering a module -

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

Below is the screenshot of the working example -



Hope this helps.




Thursday, October 8, 2015

Spinner Control For AngularJS


Introduction

In this article lets add a spinner control to show the loading of data in our AngularJS application.
I will use the same sample Web API service created in my previous article.


Practical Approach

As i said i am going to use the same Web API service and below is the project structure of AngularJS application -



Nothing fancy. It has the basic structure of AngularJS application. Now lets go through each file here in the solution -

I have a root file - "Index.html" which is my parent page and


<!doctype html>
<html>

<head>
 <title> Spinner Example </title>

</head>

<body ng-app="myApp">
 <div class="page-content">
  <div class="row">
   <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
     <ul class="nav">
      <!-- Main menu -->
      <li><a href="#/SpinnerExample"<i class="glyphicon glyphicon-home"></i> Spinner Example</a></li>
     </ul>
    </div>
   </div>
   <div class="col-md-10">
    <div class="content-box-header panel-heading">
     <div class="panel-title">Sample Spinner Example</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>

 <span us-spinner="{radius:30, width:8, length: 16}"></span>

 <!-- Libaries for Bootstrap for controls -->
 <!--Starts Here-->
 <link href="scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
 <link href="scripts/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" />
 <script type="text/javascript" src="scripts/bootstrap/js/bootstrap.min.js"></script>
 <!--Ends Here-->

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

 <link href="css/styles.css" rel="stylesheet" />
        <!-- Libaries for Spinner--> 
        <!--Starts Here-->
        <script type="text/javascript" src="scripts/spinner/spin.min.js"></script>
 <script type="text/javascript" src="scripts/spinner/angular-spinner.min.js"></script>
 <script type="text/javascript" src="scripts/spinner/angular-loading-spinner.js"></script>
        <!--Ends Here-->
        <script src="app.js"></script>
 <script src="config.js"></script>

 <script src="services/sampleService.js"></script>
 <script src="controllers/sampleController.js"></script>

</body>
</html>

This file has all relevant file paths like - controllers, scripts and services, which are required for this demo and observe the line required for spinner control is highlighted along with spinner scripts.

For demonstration purpose i have created a service - "sampleService.js", which will call the Web API
service to get the data.

myApp.service('sampleService', function ($http) {
 this.getProducts = function () {
  return $http.get('http://localhost:53308/api/Product/');
 }
});

And controller which uses the above service -

myApp.controller('sampleCtrl', ['$scope', '$http', 'sampleService', function ($scope, $http, sampleService) {
 var products = sampleService.getProducts();

 products.then(function (response) {
  //once the process data
 });

}]);

As can be seen in the above code, when the data process is completed spinner is hidden and if there is a pending http request then the spinner is shown as per the below line of code in "index.html" -

<span us-spinner="{radius:30, width:8, length: 16}"></span>

Below is the directive is used for spinner -

(function () {
 angular.module('ngLoadingSpinner', ['angularSpinner'])
    .directive('usSpinner', ['$http', '$rootScope', function ($http, $rootScope) {
     return {
      link: function (scope, elm, attrs) {
       debugger;
       $rootScope.spinnerActive = false;
       scope.isLoading = function () {
        return $http.pendingRequests.length > 0;
       };

       scope.$watch(scope.isLoading, function (loading) {
        $rootScope.spinnerActive = loading;
        if (loading) {
         elm.removeClass('ng-hide');
        } else {
         elm.addClass('ng-hide');
        }
       });
      }
     };

    }]);
}).call(this);

Below is the screenshot of the spinner in the page -



and Plunker working demo - http://plnkr.co/edit/2bkqH67BURHqPHvXFpQT?p=preview

Hope this helps.




Tuesday, October 6, 2015

Form validation in Angularjs Part - 1

Introduction

This article focuses on adding the validation on form elements. This article will cover the basic validations in AngularJS and in coming posts i will try to cover the custom validation and dynamic validations.

Approach

Lets discuss some basic form validations in AngularJS -

Below is the Angular application structure -




Here one controller - "validationController.js" is added just one HTML page - "index.html" is added for adding the form controls.


Below is the content of "index.html" -

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Validations</title>

<link href="css/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-controller="validationCtrl">

<script src="scripts/angular.min.js"></script>

<script src="app.js"></script>
<script src="controllers/validationController.js"></script>

<form name="validationForm" novalidate class="form-horizontal" ng-submit="validationViewModel.submit()">

<!-- Text Validation-->
<div class="form-group">
 <label class="col-lg-2 control-label">Name</label>
     <div class="col-sm-2">
         <input type="text" class="form-control" ng-model="validationViewModel.Name" placeholder="Enter Name" name="Name" 
              required 
              ng-maxlength="10" 
              ng-minlength="5" /> 
     </div>

     <div class="help-block" style="color:red" ng-messages="Name.$error" 
                  ng-show="validationForm.Name.$dirty && validationForm.Name.$invalid">
           <span ng-show="validationForm.Name.$error.required">Enter Name.</span>
           <span ng-show="validationForm.Name.$error.maxlength">Maximum limit reached.</span>
    <span ng-show="validationForm.Name.$error.minlength">Enter Minimum length.</span>
     </div>
</div>


<!-- Email Validation-->
<div class="form-group">
  <label class="col-lg-2 control-label">Email</label>
      <div class="col-sm-2">
           <input type="email" class="form-control" ng-model="validationViewModel.Email" placeholder="Enter Email" name="Email" 
                 required />
      </div>
   
     <div class="help-block" style="color:red" ng-messages="Email.$error" 
                ng-show="validationForm.Email.$dirty && validationForm.Email.$invalid">
          <span ng-show="validationForm.Email.$error.required">Enter Email.</span>
          <span ng-show="validationForm.Email.$error.email">Enter Valid Email.</span>
     </div>
</div>

<!-- RadioButton Validation-->
<div class="form-group">
  <label class="col-lg-2 control-label">Gender</label>
      <div class="col-sm-2">
           <input type="radio" class="form-control" ng-model="validationViewModel.Gender" placeholder="Select Gender" value="male" 
               name="Gender" 
               required />
           <input type="radio" class="form-control" ng-model="validationViewModel.Gender" placeholder="Select Gender" value="female" 
               name="Gender" 
               required />
       </div>
    
     <div class="help-block" style="color:red" ng-messages="Gender.$error" 
               ng-show="validationForm.Gender.$dirty && validationForm.Gender.$invalid">
           <span ng-show="validationForm.Gender.$error.required">Select Gender.</span>
     </div>
</div>

<div class="form-group">
  <div class="col-lg-offset-2 col-sm-8">
       <button type="submit" class="btn btn-primary" ng-click="submitted=true">Save</button>
   </div>
</div>

</form>

</body>
</html>
);

As shown above there are 3 types of validations - "Text, "Email" and "Radio button" validations.

Validations will  be done whenever the controls are changed ($dirty) and the value is invalid. ($invalid).

So suppose if you want the validations to be fired irrespective of "$dirty" flag or on the click "Save" button then we can add some tweak to the existing HTML like below -

<div class="form-group">
  <div class="col-lg-offset-2 col-sm-8">
       <button type="submit" class="btn btn-primary" ng-click="submitted=true">Save</button>
   </div>
</div>


To the existing button control add the ng-click event to make the "submitted" to true. And existing validations can be modified like below -

ng-show="submitted || (validationForm.Email.$dirty && validationForm.Email.$invalid)"> 

So do the above changes in all the places wherever it is required. This line code to check whether directly "Save" button is clicked or else follow the same validations rules.

After adding this line of code this is how our page shows -



Plunkr Demo - http://plnkr.co/edit/GHZ4sflo7IV7ynLf1wNS?p=preview

Hope this helps.




Monday, October 5, 2015

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS header 'Access-Control-Allow-Origin' missing).


Problem Statement

When working with AngularJS and Web API this issue can be seen. Lets create a sample Web API and AngularJS project to reproduce this issue and lets find the solution to this as well.

Demo

First create a sample Web API project and add - "ProductController.cs" file -

public class ProductController : ApiController
{
 private List _products;

 public ProductController()
 {
  _products = new List() { new Product() { ProductId = 1, CategoryId=100, ProductName ="Prod1"},
   new Product() { ProductId = 2, CategoryId=100, ProductName ="Prod2"}};
 }

 // GET api/product
 public List Get()
 {
  return _products;
 }

 // GET api/product/5
 public Product Get(int id)
 {
  return _products.First(a => a.CategoryId == id);
 }

 // POST api/product
 public void Post([FromBody]Product prod)
 {
  _products.Add(prod);
 }

}

Now lets create a sample html page for AngularJS application. Here lets main concentrate on the service part, which is doing a AJAX call to the Web API service -


myApp.service('sampleService', function ($http) {
 this.getProducts = function () {
  return $http.get('http://localhost:53308/api/Product/'); // Different domain call.
 }
});


As we can see in the above code. Web API running in the different domain than the client application. Below is the screenshot of error -



Solution

As a part of solution add the "<customHeaders>" tag to web config like below -

<httpProtocol>
  <customHeaders>
  <add name="Access-Control-Allow-Origin" value="*" />
  <add name="Access-Control-Allow-Headers" value="Content-Type" />
  <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
  </httpProtocol>


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




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.





Saturday, September 5, 2015

Angularjs interview questions for Freshers and Experienced

Below are the list of Angularjs interview questions for Freshers and Experienced  -


1) What are modules in AngularJS?

2)  How AngularJS application works?

3) What is the use of "$scope" in AngularJS?

4) How the Routing works in AngularJS?

5) What is the need of "service" in AngularJS?

6) How we can declare constant variables in AngularJS?

7) How we can "$http" methods in AngularJS?

8) Explain Dependency Injection in AngularJS?

9) List all the directives in AngularJS?

10) What are filters in AngularJS?

11) How the validation works in AngularJS?

12) Explain AngularJS booting process?

13) Why to use "ng-disable" directive in AngularJS?

14) How to implement a custom directive in AngularJS?

15) What is the use of "Controller as" syntax in AngularJS?



Sunday, March 8, 2015

Clearing client side validation error messages in MVC

Introduction of "Clearing client side validation error messages in MVC"
In this article i am going to explain, how to clear the client side validation messages in MVC. This post will be useful if you are using dataannotation validations in MVC. In forum we were discussing about one scenario -

When you have two buttons in a page "Save" and "Cancel" , on click of "Cancel" button say you are doing AJAX call then you might have observed that client side messages still shown in the page. You might have read my articles - Client side validation using jquery in asp.net mvc and Jquery validation plugin remove rules where i have explained alternate approach for model validations.

Approach for "Clearing client side validation error messages in MVC"
Below is the code for clearing client side validation messages in MVC -

function clearValidationMessages() {
   $('.input-validation-error').addClass('input-validation-valid');
   $('.input-validation-error').removeClass('input-validation-error');
   //removing validation message from  tag created dynamically
   $('.field-validation-error').addClass('field-validation-valid');
   $('.field-validation-error').removeClass('field-validation-error');
   $('.validation-summary-errors').addClass('validation-summary-valid');
   $('.validation-summary-errors').removeClass('validation-summary-errors');
}

Suppose you want to remove validation messages from your partialview/pop up then you can use it like this -

function clearValidationMessages() {
   $('#yourpopupID .input-validation-error').addClass('input-validation-valid');
   $('#yourpopupID .input-validation-error').removeClass('input-validation-error');
   //removing validation message from  tag created dynamically
   $('#yourpopupID .field-validation-error').addClass('field-validation-valid');
   $('#yourpopupID .field-validation-error').removeClass('field-validation-error');
   $('#yourpopupID .validation-summary-errors').addClass('validation-summary-valid');
   $('#yourpopupID .validation-summary-errors').removeClass('validation-summary-errors');
}

Hope it helps to solve your issue as well. Thanks to my colleague shwetha for discussing this issue.

Please comment below.


Tuesday, March 3, 2015

Passing anonymous object to view in ASP.NET MVC

Introduction of "Passing anonymous object to view in ASP.NET MVC"
In this article I am going to discuss about passing anonymous object to my view. In article - Dynamic view model ASP.NET MVC using ExpandoObject i elaborated method to pass dynamic view model using ExpandoObject option. So here in this article i will be reusing models and methods created in previous article.

Practical Approach for "Passing anonymous object to view in ASP.NET MVC"
Now lets dive into practical approach of passing anonymous object to view. As mentioned i will be reusing classes created in the previous article. i.e, Class" and "Student" -
public class Class
{
 public int ClassID { get; set; }
 public string ClassName { get; set; }
}

public class Student
{
 public int StudentID { get; set; }
 public int ClassID { get; set; }
 public string StudentName { get; set; }
}
HomeController after updating looks like this -
public ActionResult Index()
{
 List classes = new List()
 {
  new Class() {ClassID =1, ClassName = "Class1"},
  new Class() {ClassID =2, ClassName = "Class2"},
  new Class() {ClassID =3, ClassName = "Class3"}
 };

 List students = new List()
 {
  new Student() {StudentID = 100, ClassID =1, StudentName = "Student1"},
  new Student() {StudentID = 101, ClassID =1, StudentName = "Student2"},
  new Student() {StudentID = 102, ClassID =1, StudentName = "Student3"},
  new Student() {StudentID = 103, ClassID =2, StudentName = "Student4"},
  new Student() {StudentID = 104, ClassID =2, StudentName = "Student5"},
  new Student() {StudentID = 105, ClassID =3, StudentName = "Student6"}
 };

 IEnumerable studentList1 = students.Where(s => s.ClassID == 1);

 return View(studentList1);
}

As you can see in the above code snippet, I am trying to filter the list students based on Class ID. And my Index view is updated like below -

@model IEnumerable<dynamic>

@{
 ViewBag.Title = "Home Page";
}


<p><b>Student Details</b></p>

<table>
 <tr>
  <th>StudentID</th>
  <th>StudentName</th>
 </tr>
 @foreach (DynamicModelusingAnonymousobjects.Models.Student s in Model)
 {
  <tr>
   <td>@s.StudentID</td>
   <td>@s.StudentName</td>
  </tr>
 }
</table> 

So here in the above code snippet i am trying to bind the students in Class ID = 1. Below is the screenshot of output from my application -


Passing anonymous object to view in ASP.NET MVC
Passing anonymous object to view in ASP.NET MVC

Hope this article is helpful.


Sunday, March 1, 2015

Dynamic view model ASP.NET MVC using ExpandoObject


Introduction of Dynamic view model ASP.NET MVC using ExpandoObject

In this "Dynamic view model ASP.NET MVC using ExpandoObject" article I am going to explain about passing dynamic model to our view in mvc. Here I am trying to use "ExpandoObjects". This has been introduced in .NET 4.0 version. An ExpandoObject object helps us to add or remove members dynamically at runtime.

Note: This article is just to give a information on how we can use dynamic models in mvc using ExpandoObject. But I am strictly against this approach as we can handle these stuffs with different approach as well (without using "ExpandoObject", i will discuss those approaches in the coming weeks though).

Now lets dive in to the practical approach of using dynamic view model using ExpandoObject.

Lets create new classes - "Class" and "Student" to demonstrate this -
public class Class
{
 public int ClassID { get; set; }
 public string ClassName { get; set; }
}

public class Student
{
 public int StudentID { get; set; }
 public int ClassID { get; set; }
 public string StudentName { get; set; }
}
So now lets update the existing Homecontroller to use "ExpandoObject". So below is the updated code -

public ActionResult Index()
{
 dynamic mymodelDetails = new ExpandoObject();
 
 List classes = new List()
 {
  new Class() {ClassID =1, ClassName = "Class1"},
  new Class() {ClassID =2, ClassName = "Class2"},
  new Class() {ClassID =3, ClassName = "Class3"}
 };

 List students = new List()
 {
  new Student() {StudentID = 100, ClassID =1, StudentName = "Student1"},
  new Student() {StudentID = 101, ClassID =1, StudentName = "Student2"},
  new Student() {StudentID = 102, ClassID =1, StudentName = "Student3"},
  new Student() {StudentID = 103, ClassID =2, StudentName = "Student4"},
  new Student() {StudentID = 104, ClassID =2, StudentName = "Student5"},
  new Student() {StudentID = 105, ClassID =3, StudentName = "Student6"}
 };

 //mymodelDetails.Classes = new { Classes = classes }.ToExpando();
 //mymodelDetails.Students = new { Students = students }.ToExpando();

 mymodelDetails.Classes = classes;
 mymodelDetails.Students = students;

 return View(mymodelDetails);
}

So as you can see in the above code snippet, data are populated for these classes and two properties "Classes" and "Students" are added to my dynamic expandoobject - "mymodelDetails".

So these "ExpandoObject" properties are used in the existing Index.cshtml as below -

@model dynamic
@{
    ViewBag.Title = "Home Page";
}

Class Details
<table> <tr> <th>ClassID</th> <th>ClassName</th> </tr> @foreach (PassingDynamicModel.Models.Class c in Model.Classes) { <tr> <td>@c.ClassID</td> <td>@c.ClassName</td> </tr> } </table> <br/> <br />
Student Details
<table> <tr> <th>StudentID</th> <th>StudentName</th> </tr> @foreach (PassingDynamicModel.Models.Student s in Model.Students) { <tr> <td>@s.StudentID</td> <td>@s.StudentName</td> </tr> } </table>

After Executing this we get output like below -

Dynamic view model ASP.NET MVC using ExpandoObject

Hope this article is useful.


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.