Friday, 16 September 2016

Filters and attributes in asp.net mvc5

Leave a Comment
The main goal of this tutorial is explain about basic understanding of Action filters in asp.net mvc5. ASP.NET MVC framework provides a simple way to inject your piece of code or logic either before or after an action is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters(filter interface) and can contain your piece of code or logic. You can make your own custom filters or attributes either by implementing ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.

Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.
  1. Custom Authentication
  2. Custom Authorization(User based or Role based)
  3. Error handling or logging
  4. User Activity Logging
  5. Data Caching
  6. Data Compression

Types of Filters

The ASP.NET MVC framework provides five types of filters.
  1. Authentication filters (New in ASP.NET MVC5)
  2. Authorization filters
  3. Action filters
  4. Result filters
  5. Exception filters
  6. Authentication Filters
This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-
public interface IAuthenticationFilter
{
 void OnAuthentication(AuthenticationContext filterContext);

 void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
 public void OnAuthentication(AuthenticationContext filterContext)
 { 
 //Logic for authenticating a user
 }
 //Runs after the OnAuthentication method
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
 { 
 //TODO: Additional tasks on the request
 }
}

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-
public interface IAuthorizationFilter
{
 void OnAuthorization(AuthorizationContext filterContext);
}
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
 protected virtual bool AuthorizeCore(HttpContextBase httpContext);
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
 public virtual void OnAuthorization(AuthorizationContext filterContext);
 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}
In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.
Action Filters
Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.
public interface IActionFilter
{
 void OnActionExecuting(ActionExecutingContext filterContext);
 void OnActionExecuted(ActionExecutedContext filterContext);
}

 Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.
public interface IResultFilter
{
 void OnResultExecuted(ResultExecutedContext filterContext);
 void OnResultExecuting(ResultExecutingContext filterContext);
}

 Exception Filters

Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.
public interface IExceptionFilter
{
 void OnException(ExceptionContext filterContext);
}
ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.
Order of Filter Execution
All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:
  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters

Configuring Filters in application

You can configure your own custom filter into your application at following three levels:
Global level
By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.
protected void Application_Start()
{
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
Controller level
By putting your filter on the top of the controller name as shown below-
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
 //
}
Action level
By putting your filter on the top of the action name as shown below-
public class UserController : Controller
{
 [Authorize(Users="User1,User2")]
 public ActionResult LinkLogin(string provider)
 {
 // TODO:
 return View();
 }
}

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Wednesday, 14 September 2016

How to optimize performance using Bundling and Minification in mvc5

Leave a Comment

What is Bundling

Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load  performance.

Minification

Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character.

To implement  bundling and minification in ASP.NET 4.5 version first we need to add the references of System.Web.Optimization.dll and WebGrease.dll to your MVC3 and Asp.Net 4.5 projects.

What is a Bundle

A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script bundle for css and javascripts respectively by calling BundleCollection class Add() method with in BundleConfig.cs file.In Dot net framework System.Web.Optimization class offers the bundling and minification techniques that is exist with in the Microsoft.Web.Optimization dll.


1.To implement bundling we create a BundleConfig.cs file in App_start folder.
2.Add reference dll files from nuget package manager console.

microsoft web optimization
webgrease

3.Now import reference class in  BundleConfig.cs.
4.I added some styles and script bundles using static RegisterBundles methods.
5.See below..
using System.Web;
using System.Web.Optimization;

namespace BundlingDemo
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

We can also add CDN files to the bundling using below code..
public static void RegisterBundles(BundleCollection bundles)
{
    //enable CDN support
    bundles.UseCdn = true;   

    //add link to jquery on the CDN
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));
}

Note:Here in above code you may come across this symbol"*".It is wildcard character is used to combines the files that are in the same directory and have same prefix or suffix with its name. Suppose you want to add all the scripts files that exist with in "~/Script" directory and have "jquery" as prefix then we can simply represent them with wildcard symbol like below.
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery*.js"));
6.This is process is same for css files also.Ex:
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));
7.To register all bundles in Application_Start event in Global.asax file.we need to add line of code
BundleConfig.RegisterBundles(BundleTable.Bundles);
protected void Application_Start()
{
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 // Other Code is removed for clarity
}
8.Now you can add the above created style and script bundles to the Layout page or where you want to use as shown below.
@System.Web.Optimization.Styles.Render("~/Content/css")
@System.Web.Optimization.Scripts.Render("~/bundles/jquery")

Minification

1.There are so many tools for minifying the js and css files online. JSMin and YUI Compressor are two most popular tools for minifying the js and css files or you can also install WebEssential extension tool to visual studio to minify the files.

Lets check the performance optimization with and without Bundling and minification in asp.net mvc sample web application.I done test performance test using Chrome web developer tools with below css and script files in _Layout.cshtml page.


<link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/Site.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.js"></script>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/respond.js"></script>
2.It took below time to load without bundling and minification.

without optimization-in-mvc5
3.With optimization...

with web optimization
4.In first test there are 13 requests and load time is 5.42seconds.
5.When using optimizations the requests are 11 and load time decreased to 454 milli seconds what a change there is lot of reduction in load time..
6.And it also improves the browser caching ..

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Understanding Scaffolding in ASP.NET MVC

Leave a Comment

What is Scaffolding

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications to facilitate the rapid application development.From Visual Studio 2013 and newer versions of visual studio  includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.

This scaffolding is also used by many other MVC frameworks like Ruby on Rails, Cake PHP and Node.JS etc to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively. Further you can edit or customize this auto generated code according to your need


Prerequisites for Scaffolding

To use ASP.NET Scaffolding, you must have below tools installed in system.Do not bother about this these are automatically installed while visual studio(from VS13 on wards) installation.For older versions like vs 2010,2008 need to be manually installed.
  • Microsoft Visual Studio 2013 or higher
  • Web Developer Tools (part of default Visual Studio 2013 installation)
  • ASP.NET Web Frameworks and Tools 2013 (part of default Visual Studio 2013 installation)
In ASP.NET MVC these scaffolding code is generated against the database with help of Entity Framework (a Object relational mapping framework to work with DB logic).These templates use the Visual Studio T4 templating system to generate views for basic CRUD operations with the help of Entity Framework.

Steps to add Scaffolding to create CRUD operations in MVC

1.Add a Controller to web application.

adding-scaffolding-item

2.Select below template from Visual studio 2013.

adding-controller-with-actions-and-views
3.Select Model class and context class from Drop downs in Add Controller window.

Adding-Model-class-and-Datacontextclass
4.After that visual studio automatically creates all actions methods and view for CRUD operations with help of entity framework.
5.See the folder created in solution explorer below.

scaffoladed-view-with-actions

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 13 September 2016

A Brief discussion on Render,Layout pages in ASP.NET MVC

Leave a Comment
Hi Every one Welcome again with new tutorial.In this tutorial i am going to tell a brief description about Layout pages,Render pages,Will explain about What is Render.Body() and Render Section etc.

Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a simple syntax and greater flexibility.
The below is HTML markup is the Basic structure of Layout page
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width" />
 <title>@ViewBag.Title</title>
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")
</head>
<body>
 @RenderBody()

 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>
</html>
In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for defining the default Layout page for your ASP.NET MVC application.

Styles.Render and Scripts.Render

Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render is also used to render a bundle of Script files by rendering script tag(s) for the Script bundle.
Example:


public class BundleConfig
{
 public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
 "~/Scripts/jquery.unobtrusive*",
 "~/Scripts/jquery.validate*",
"~/Scripts/jquery.min.js"));
 
 bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
 "~/Content/themes/base/jquery.ui.core.css",
 "~/Content/themes/base/jquery.ui.resizable.css",
 "~/Content/themes/base/jquery.ui.theme.css"));
 }
} 
Important :
1.Styles.Render and Scripts.Render generate multiple style and script tags for each item in the CSS bundle and Script bundle when optimizations are disabled.
2.When optimizations are enabled, Styles.Render and Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire bundle for CSS and Scripts.
3.You can enable and disable optimizations by setting EnableOptimizations property of BundleTable class to true or false with in Global.asax.cs file as shown below.
protected void Application_Start()
{
 //Other code has been removed for clarity
 System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
RenderBody()
RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder in master page. A layout page can have only one RenderBody method.
RenderPage()
RenderPage method also exists in the Layout page to render other page exists in your application. A layout page can have multiple RenderPage method.
Example:
Example for Rendering page syntax is below.
@RenderPage("~/Views/Shared/_Header.cshtml")

What is Section

A section allow you to specify a region of content within a layout. It expects one parameter which is the name of the section. If you don’t provide that, an exception will be thrown. A section in a layout page can be defined by using the following code.
Ex: For example we can make<head> as one section and <body> as another section like that.see below example syntax.
@section header{
<h1>Header Content</h1>
}

<!--we can render above code using below-->
@RenderSection("header")

5.We can make this sections are optional(by default they are mandatory sections) by specifying passing a Boolean (false) parameter in RenderSection() method.

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].


Wednesday, 7 September 2016

Angular Text Editor in asp.net mvc5 web application

Leave a Comment
Hi every one welcome again thank yo for  comments and recommendations for previous post.In today's tutorial i am going to teach you How to integrate Angular Text Editor in asp.net mvc5 web application.This Text Editor is an angular plugin that can make a text area html element into Text Editor.This is WYWIWYS type of Text Editor.
In computing, a WYSIWYG editor is a system in which content (text and graphics) displayed onscreen during editing appears in a form closely corresponding to its appearance when printed or displayed as a finished product, which might be a printed document, web page, or slide presentation. WYSIWYG is an acronym for "what you see is what you get".
Let see some of  my previous posts,
Now see how to implement Angular Text Editor in our asp.net mvc web application.
1.Create asp.net web application using empty mvc template.

Create a Controller

1.Right click on Controllers folder --> add --> Controller--> name it.
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
2.Add View to the Index action method by right click on index action --> Add View --> name it --> add.
3.Add below reference files that are required for Angular Text editor.
<!--Angular Text Editor Reference files-->
<link href="http://jqueryte.com/css/jquery-te.css" rel="stylesheet"/>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://jqueryte.com/js/jquery-te-1.4.0.min.js"></script>

Add angular script code for Text Editor

4.Add below angular script to make text area as Text Editor.
5.Here,i am storing the text editor data in $scope.descriptionzone and displaying HTML output of the data in below Text Editor.
 function Controller($scope) {
        //object that stores the editor (textbox) data.
        $scope.descriptionzone = undefined;
        //resets the Editor data
        $scope.reset = function () {
            $scope.descriptionzone = null;
        }
    };

    angular.module('angularteexample', []).directive('angularte', function () {
        return {
            restrict: 'A',
            require: '^ngModel',
            link: function (scope, element, attrs, ngModel) {
                $(function () {
                    element.jqte({
                        // On focus show the toolbar
                        focus: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").show();
                                element.parents(".jqte").click(function () { element.parents(".jqte").find(".jqte_toolbar").show(); });
                            });
                        },
                        // On blur hide the toolar
                        blur: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").hide();
                            });
                        },
                        // On change refresh the model with the textarea value
                        change: function () {
                            scope.$apply(function () {
                                ngModel.$setViewValue(element.parents(".jqte").find(".jqte_editor")[0].innerHTML);
                            });
                        }
                    });
                    element.parents(".jqte").find(".jqte_toolbar").hide();
                });

                // On render refresh the textarea with the model value 
                ngModel.$render = function () {
                    element.parents(".jqte").find(".jqte_editor")[0].innerHTML = ngModel.$viewValue || '';
                };
            }
        }
    });

6.See the complete code of the Index below.

@{
    ViewBag.Title = "www.mitechdev.com";
}
<h3>Angular Text Editor in asp.net mvc5 application</h3>
<!--Angular Text Editor Reference files-->
<link href="http://jqueryte.com/css/jquery-te.css" rel="stylesheet"/>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://jqueryte.com/js/jquery-te-1.4.0.min.js"></script>

<script>
    function Controller($scope) {
        //object that stores the editor (textbox) data.
        $scope.descriptionzone = undefined;
        //resets the Editor data
        $scope.reset = function () {
            $scope.descriptionzone = null;
        }
    };

    angular.module('angularteexample', []).directive('angularte', function () {
        return {
            restrict: 'A',
            require: '^ngModel',
            link: function (scope, element, attrs, ngModel) {
                $(function () {
                    element.jqte({
                        // On focus show the toolbar
                        focus: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").show();
                                element.parents(".jqte").click(function () { element.parents(".jqte").find(".jqte_toolbar").show(); });
                            });
                        },
                        // On blur hide the toolar
                        blur: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").hide();
                            });
                        },
                        // On change refresh the model with the textarea value
                        change: function () {
                            scope.$apply(function () {
                                ngModel.$setViewValue(element.parents(".jqte").find(".jqte_editor")[0].innerHTML);
                            });
                        }
                    });
                    element.parents(".jqte").find(".jqte_toolbar").hide();
                });

                // On render refresh the textarea with the model value 
                ngModel.$render = function () {
                    element.parents(".jqte").find(".jqte_editor")[0].innerHTML = ngModel.$viewValue || '';
                };
            }
        }
    });
</script>
<div ng-app="angularteexample">
    <div ng-controller="Controller">
        <p>
            <!--Text Editor element-->
            <textarea angularte ng-model="descriptionzone"></textarea>
        </p>
        <p>Test: 
            <!--it shows the data we entered in Editor-->
            <!--Here it shows the Html output of the Editor data-->
            <div style="background-color:darkgreen;color:white;">{{descriptionzone}}</div>
        </p>
        <p>Click Reset button to reset the Editor: <button type="button" class="btn btn-default" ng-click="reset()">Reset Editor</button></p>
    </div>
</div>


7.For more information about this Angular TextEditor visit official page www.jqueryte.com.
8.See the output of the application.
Angular Text Editor in asp.net mvc5 web application

9.The below is html output of the text editor data.
10.when click on Reset Edior button the in editor is erased.
11.Downlaod the source code of the application Source Code (VS15).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 6 September 2016

How to display attrative tooltips using Tispo jquery plugin in mvc5

Leave a Comment
In this article i am going to introduce a new jquery plugin for attractive tool tips.we are seeing tool tips in many of the websites to simplify user understand of the application.So,I searched for jquery plugin that is best suitable for web applications which are build by asp.net mvc framework.we can also use this Tispo jquery plugin in non microsoft technologies like JAVA,PHP.It is very easy to use.We can also apply animations,effects and can bind actions also.
Now see how we are going to use this plugin in our asp.net mvc web application.

Required Files:

<!--Jquery script plugins-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--Tipso plugin references-->
<link rel="stylesheet" href="http://tipso.object505.com/tipso.css">
<script src="http://tipso.object505.com/tipso.js"></script>
<link rel="stylesheet" href="http://tipso.object505.com/animate.css">
Note: Before adding this files in view remove the jquery reference from _Layout.cshtml page in Shared folder in Views  folder.

Create Controller and add view

1.Right click on Controllers folder --> add -->Controller(i named as HomeController).
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
2.Add View to Index action method with empty view template.
3.Add above reference files to the Index view.
$("#top-right").tipso({
            //position where we should display the tooltip on link
            position: 'top-right',
            //background color of the text
            background: 'rgba(0,0,0,0.8)',
            //color of title
            titleBackground: 'tomato',
            //Content should display in title
            titleContent: 'Top Right',
            useTitle: false,
            //enabling hover effect
            tooltipHover: true,
            //animation occurs when we place cursor on link
            animationIn: 'tada',
            //animation occurs when we remove the cursor on link
            animationOut: 'flash'
        });
4.Replace the complete view code with below code.
@{
    ViewBag.Title = "Index";
}

<h2>Jquery attractive Tooltips using Tispso plugin</h2>
<!--Jquery script plugins-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--Tipso plugin references-->
<link rel="stylesheet" href="http://tipso.object505.com/tipso.css">
<script src="http://tipso.object505.com/tipso.js"></script>
<link rel="stylesheet" href="http://tipso.object505.com/animate.css">

<script type="text/javascript">
    $(document).ready(function () {
        $("#top-right").tipso({
            //position where we should display the tooltip on link
            position: 'top-right',
            //background color of the text
            background: 'rgba(0,0,0,0.8)',
            //color of title
            titleBackground: 'tomato',
            //Content should display in title
            titleContent: 'Top Right',
            useTitle: false,
            //enabling hover effect
            tooltipHover: true,
            //animation occurs when we place cursor on link
            animationIn: 'tada',
            //animation occurs when we remove the cursor on link
            animationOut: 'flash'
        });
        $("#top-left").tipso({
            position: 'top-left',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'tomato',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'tada',
            animationOut: 'flash'
        });
        $("#right").tipso({
            position: 'right',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'green',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'bounceIn',
            animationOut: 'bounceOut'
        });
        $("#destroy-tooltip").tipso({
            position: 'bottom',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'green',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'fadeIn',
            animationOut: 'shake'
        });
        //destroy tooltip
        $("#btn-destroy").on('click', function (e) {
            $("#destroy-tooltip").tipso('destroy');
            e.preventDefault();
        });
    });
</script>
<div>
    <p>
        1.<a id="top-right" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">         
              www.mitechdev.com</a> is a good programming blog(Top-right)
    </p>
    <p>
        2.<a id="top-left" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog(Top-left)
    </p>
    <p>
        3.<a id="right" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog
    </p>
    <p>
        4.<a id="destroy-tooltip" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog<input type="button" class="btn btn-default" id="btn-destroy" value="destroy tooltip"/>
    </p>
</div>

5.To destroy the tool tip use below code..
 //destroy tooltip
        $("#btn-destroy").on('click', function (e) {
            $("#destroy-tooltip").tipso('destroy');
            e.preventDefault();
        });
6.Finally run the application and see the output in browser.
How to display attrative tooltips using Tispo jquery plugin in mvc5
7.for right and top-left will be like this..

How to display attrative tooltips using Tispo jquery plugin in mvc5
Download source code for this application Source Code(VS2015).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Monday, 5 September 2016

Partial Views in ASP.NET MVC5

1 comment
In this article i will explain about What is partial views and How to use partial views in ASP.NET MVC5 web application.Some newbies who are new to asp.net mvc development might think that partial views are similar to user controls in ASP.NET web forms.Both are used for same cause Re usability and design but the implementation is different.

what is Partial View:

Partial view is special view which renders a portion of view content.Partial can be reusable in multiple views. It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view.
The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view.So,it can access the data of parent view.

How to create a partial view
To create a Partial View Right click on any folder(recommend to use shared folder in Views folder.Because by default MVC engine looks for Views in this folders) --> Add --> Select MVC5 Partial page(in VS2015).
For older versions of visual studio (from 2010 to 2013) there is no direct template for partial view.
So,follow this step Right click on folder --> select View template --> Check partial view checkbox -->add.

Partial Views in ASP.NET MVC5
In asp.net mvc5 we have 4 ways to access or render the partial views.
They are,
1.@Html.RenderPartial,
2.@Html.Partial,
3.@Html.RenderAction
4.@Html.Action
Example code:
<div>  
    @Html.Partial("PartialViewExample")  
</div>  
<div>  
    @{  
        Html.RenderPartial("PartialViewExample");  
    }  
</div> 
@Html.RenderPartial
The result of the Render Partial method is written directly into the HTTP response, it means that this method used the same TextWriter object as used by the current view. This method returns nothing(type:void).We can store the output of partial in cache.
@Html.Partial
This method renders the view as an HTML-encoded string. We can store the method result in a string variable.The Html.RenderPartial method writes output directly to the HTTP response stream so it is slightly faster than the Html.Partial method. It can not be cached.We can also return partial view using method from Controller like below.
public ActionResult PartialView()  
{  
    return PartialView();  
} 

@Html.Action
This action is useful when the display data in thee partial view is independent from corresponding view model.
Example:
@Html.Action("User_View")
Html.RenderAction
This action is also works same as Html.Action...
Render Partial View Using Jquery
Sometimes we need to load a partial view within a model popup at runtime(Mainly in real application development), in that case we can render the partial view using JQuery element's load method like below.
<script type="text/jscript">  
        $('#partialView').load('/shared/PartialViewExample’);  
</script> 

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].