All posts by Thiyagu

How to Persist Data with TempData using Peek and Keep in MVC

In this post we are going to discuss about how to preserve the value in next request using TempData Peek and Keep in ASP.NET MVC.

What is TempData?

Tempdata helps to store/preserve values within in a single request. This is the one of the concept for maintaining state in ASP .Net MVC.

How to store/persist data in next request?

TempData preserve values for the next request in 4 different conditions in MVC. They are

  • Condition 1 – Not Read in First Request.
  • Condition 2 – Read In First Request.
  • Condition 3 – Read & persist using Keep.
  • Condition 4 – Persist using Peek and Read.

Let us discuss this one by one in detail.

Not Read in First Request : If we do not read “TempData” in the current request then “TempData” value will be persisted for the next request.
Read In First Request : If we read “TempData” in the current request then “TempData” value will be not persist for the next request.
Read & Persist using Keep : If we read “TempData” in the current request and we can keep method to persist TempData for the next request. In MVC, we are having void keep() and  void keep(string key) methods to persist the data.

Example :

var readInfo = TempData

[“dotnet-helpers-info”];
TempData.Keep(“dotnet-helpers-info”);
OR
var readInfo = TempData[“dotnet-helpers-info”];
TempData.Keep();

Persist using Peek and Read : If we read “TempData” using the Peek method then then the data will persist in the next request.

Example :

var readInfo = TempData.Peek(“dotnet-helpers-info”);

Flow Chart

https://dotnet-helpers.com/wp-content/uploads/2015/11/TempdatawithKEEPandPEEK-Dotnet-helpers.com-1-1.jpg

Server-Side Comment in MVC

In this post we are going to discuss about new feature in mvc, that is server-side comment.

What is Client side comments?

(<!– –>) it is a Comment which is support by HTML. It main purpose to prevent a browser from running or displaying the code/content in the application.

What is Server Side Comments?

In ASP.NET MVC supports a server-side comment which make code/content completely disable in the page.

ASP.NET Web Forms supports a server-side comment that you can use to completely disable content/code within a page. Using this compiler completely ignore everything within the @*– –*@ blocks at parse time, and removes the content completely when assembling the page in the browser(in simple it won’t show the content/code in the browser). So the contents wasn’t there at the page while loading in browser.

Syntax for Server side comment :

MVC Razor : @*– –*@
ASP WebForm : <%– –%>

Why Server Side Comments is needed?

The problem with using Client side comments approach, is that the content contained within the comment in our application is still sent to the client from the server unnecessarily.Then the server-side code within the comment will still execute. This will create extra load to the server. To overcome this scenario we moved to the server side comments

Example: Client Side Comment

Include <!–<h1>Bundling in dotnet-helpers.com</h1>–> in view/form, then the output will be

Example: Server Side Comment

Include @*<h1>Bundling in dotnet-helpers.com</h1>*@ in view/form, then the output will be

Note :

  •  In Client Side Comment, the commented code/content will be loading to the browser side as shown in example above
  •  In Server Side Comment, the commented code/content will not be load to the browser side as shown in example above

Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC

What is Layout?

The main focus of the developers will be to maintain a consistent look and fell across the application (ie., all the pages within our website/application). To achieve this, Razor View Engine support a concept with a feature called “layouts”. Which can allow us to define a common template, and then we can able to inherit its look and feel across all the views/pages on our Application to make consistent look and feel.

MVC layout is same like as masterpage concept in webforms.

1. RenderBody:

What is it?

As per below example, the layout view contains html Doctype, head and body elements as like other view/page. The main difference is call to RenderBody() and RenderSection() methods in the layout.

RenderBody acts like a placeholder for other views. For example, Index.cshtml is a view which rendered layout view,where the RenderBody() method is being called.

Syntax : @RenderBody()

Example :

_Layout.cshtml

<!DOCTYPE html>
<html>
<head><title></title></head>
<body><div class=”body-content”>@RenderBody()<footer> …</footer></div>
</body>
</html>

Index.cshtml

//We can render layout in our view by calling “Layout=~/Views/Shared/_Layout.cshtml”

@{ Layout=~/Views/Shared/_Layout.cshtml}

//The below content will be render inside the @RenderBody section in layout

<div><h5>This content will be placed in the @RenderBody() section</h5></div>

2. RenderSection

What is it?

The layout have only contain one RenderBody method, but can have multiple sections. RenderSection method is used to create sections in layout. RenderSection runs code blocks which we define in our content pages.

Syntax : @RenderSection(“section name”, Boolean value)

Explanation :

In ASP.NET MVC by default, sections are mandatory. To handle this/make this optional, just we need to utilize the second parameter “false”.

@RenderSection(“scripts”, false) – Make the Scripts-RenderSection non-mandatory in all the pages/views which included  _Layout.cshtml

@RenderSection(“scripts”, true) – Make the Scripts-RenderSection mandatory in all the pages/views which included  _Layout.cshtml

Example :

_Layout.cshtml

<!DOCTYPE html>
<html>
<head><title>….</title></head><body><div class=”body-content”>
@RenderBody()
@RenderSection(“scripts”, required: false)
</div>
</body>
</html>

Index.cshtml

@{ Layout=~/Views/Shared/_Layout.cshtml}

@section scripts {<script type=”text/javascript”>alert(‘Dotnet-helpers’);</script>}

3. RenderPage

What is it?

RenderPage method is used to render other exists view in our application.In simple, the method allows us to render
code from an other view.
A layout page can have multiple RenderPage method.

Syntax: @RenderPage(“~/Views/Shared/_LoginPartial.cshtml”,model)

Explanation :

This method takes either one or two parameters.The first parameter refer the physical location of the file and second is an optional array of objects/model that can be passed into the view.

Where to Use?

If we want to keep the footer and header in separate view. In this scenario, we need to call two separate view in to the layout using RenderPage method.

Example:

Create two view partial views under the shared folder to make it as shared.

view 1 : _Header.cshtml
view 2 : _Footer.cshtml

_Layout.cshtml :

<!DOCTYPE html>
<html>
<head><title>….</title></head><body>
<div class=”header-content”>@RenderPage(“~/shared/_Header.cshtml”)</div>
<div class=”body-content”>@RenderBody()</div>
<div class=”header-content”>@RenderPage(“~/shared/_Footer.cshtml”)
</div>
</body>
</html>

Points to Remember :

  • The layout have only contain one RenderBody method, but can have multiple sections.
  • RenderSection runs code blocks which we define in our content pages.
  • RenderPage method is used to render other exists view in our application.

Bundling and minification

From which version ?

We can use Bundling and minification from ASP.NET 4.5 (ASP.NET MVC 4). In MVC3 and Asp.Net 4.0 application we can utilize by including System.Web.Optimization.dll and WebGrease.dll reference to our projects  and we can create the bundle for .css and .js files with in the Global.asax file.

What is it?

Bundling: It’s a group of js and css files that could be referred by unique name.
Purpose: The main usage of bundling is, it being loaded with one HTTP request instead of multiple request for each file.

Minification : It’s main process is removing of unnecessary white-space from the js and css files.
Purpose: The main purpose is to remove line break and comments from code and improving load times by reducing its size of the file.

Work with Example: 

Let we start to discuss with the simple example of working process for bundling with js files.

Example 1: Without Bundling

Step :1

In our example, i had referred five following script files in the “index.cshtml” view.

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>

Step :2

Run the application and see the output for the request in browser as shown below. Each files request make their own time. Totally they spend 513 millisecond to load all files(ie., 0.513 seconds).

From the above image, we understood the page request five time for loading script file . To reduce this loading time we have moving to bundling concept. Let we dicuss with sample exmple

Example 2: Using Bundling

Step :1

Instead of refering all the files in view, we moving them together in BundleConfig.cs file in App_Start folder like below

public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{

bundles.Add(new ScriptBundle("~/bundles/dotnet-helpers-scripts").Include(
"~/Scripts/jquery-1.8.2.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/knockout-2.2.0.debug.js",
"~/Scripts/knockout-2.2.0"));

//For adding css use below piece of code. Add css files after removing all white-space and line break to achieve minification

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

All the files has been included under the unique name dotnet-helpers-scripts.so if we want to call these all js files in view, then we will call using bundle file name “dotnet-helpers-scripts”

Step :2

Be aware these two things has been included in Application_Start method in Global.asax file in the application

protected void Application_Start()
{
BundleTable.EnableOptimizations = true;
BundleConfig.RegisterBundles(BundleTable.Bundles);
....
}

Step :3

Here we calling the bundle dotnet-helpers-scripts which contain all 5 files. So here the request will only once while site loading

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
@Scripts.Render("~/bundles/dotnet-helpers-scripts")
</head>
<body>
<div>
<h1>Bundling in dotnet-helpers.com</h1>
</div>
</body>
</html>

Step : 4

Run the application to see the output difference using browser debugger mode

Form above image, all files are bundled in one (ie., dotnet-helpers-scripts). Instead of loading five .js files, it has been loaded with single dotnet-helpers-scripts bundle. so its taking only 63 millisecond (0.063 second) to load.

Minification :

In same way we can also include the .css files in bundling. We need to remove all the white-space and commands as shown in below example

Example:

body{background-color: #fff;border-top: solid 10px #000;color:#333;font-size:.85em;font-family:”Segoe UI”, Verdana,Helvetica,Sans-Serif;margin:0;padding:0;}…..

For css we use @Styles.Render(“….”) instead of @Script.Render(“….”) and  bundles.Add(new StyleBundle(“~/Content/css”).Include(“~/Content/site.css”)) instead of  bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(“~/Scripts/…”));

Keep cool coding….

Different ways of rendering layout in MVC

What is Layouts?

Layouts is same like as form which may used commonly among all the pages. Layout are like Master page in web form.

What is the use?

Using Layouts, we can maintain consistent look and feel across the pages/views within our site/application. It contains common html,css,content…

Rendering layout in different ways :

Let we discuss about the different ways of rendering layout in our forms.

Render Layout 1 : Mention Layout with in each view on the top

The default layout has been added while creating the view. We can override the default layout by assigning our own layout like as shown below

@{
Layout = “~/Views/Shared/_CustomerLayout.cshtml”;
}

Render Layout 2 : Returning the Layout in controller –> ActionResult

Here we can override default layout by rendering the layout from the ActionResult. From below code, the layout _customerLayout has been replaced in the Index view.

public ActionResult Index()
{
….
return View(“Index”, “_CustomerLayout”, model);
}

Render Layout 3 : Define _ViewStart in each Folder/directory

We can set default layout for particular directory/folder by creating _ViewStart file in each of the directories/folder with the piece of code as shown below

@{
//Name of the Layout which want to be set as default
Layout = “~/Views/Shared/_Layout.cshtml”;

}

 

After creating _viewStart.cshtml in each directory, it will be set as default layout while creating new view in the same directory.

Keep cool coding….

 

jQuery DOM Traversing

JQuery is a powerful framework which provides very flexible DOM traversal methods to help us by selecting the elements. We can select the element by two ways namely random and sequential method. In simple word, we can traverse deeper into the DOM with the help of query traversing methods. Mainly traversing can be categorized in three ways. They are,

Parent traversing

The jQuery methods used for finding their parents elements are,

[su_table]
 .parent() selects only one element in the DOM tree.
 .parents() It will function same like parent() method but it select all the element up to the DOM tree
 .parentsUntil() It will traverse and find ancestors of each element in the current set of matched elements
 .closest(). selects the first element that matches the selector

[/su_table]

Children traversing

. Childrent () and.Find () methods are used for finding the child elements from the selection. The main difference between these two methods depend up on how far they traversing is made.

[su_table]
 .Children()  Find on direct child nodes
 .find() It can traverse in to children, children of those children so on. It operate recursively.

[/su_table]

Siblings traversing

The last traversal method is siblings. The siblings (each of two or more children or offspring having one or both parents in common; a brother or sister.)  methods traversal as the name implies by its.

[su_table]
.prev() It will find one element previous to selected element
.next() It will find one element next to selected element
.siblings() It will perform both the .prev and  .next operation
.nextAll() It will select all the element next to selected object

[/su_table]

We can find previous elements by using.Prev() method & next elements with .Next (), and both with .Siblings().

Note:

  • Traversal methods do not alter/modify the objects. They’re mainly used to filter the elements of  DOM object.

Let us discuss details about all traverse method with examples in up-coming posts.

 

Keep Cool Coding…

 

What is Attribute? How to get Attribute from HTML Element?

What is Attribute in JQuery?

All HTML elements have attributes. It provides additional information about an element. Let us see some example of attributes below.

  • class Name
  • id
  • title
  • name
  • src
  • style

Consider the HTML markup for an div element.

<div id='divUserEmailId' class=''txtclass'> 
</div>

In the above HTML markup id, class are represents the element’s attributes, which consists of a name and a value. Jquery provide an easy way to manipulate the element attributes by using selectively.

How to get Attribute Value?

The attr() method can be used to either fetch the value of an attribute or perform the assigned operation on the onto all matched elements.

Example :

<h2>Jquery Attribute Example</h2>
<html>
<head>
<title>JQuery-Helpers</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(".jQClass").attr("title", "JQuery-Helpers");
});
</script>
</head>
<body>
<div class="jQClass"></div>
<div class="jQClass"></div>
<div class="jQClass"></div>
</body>
</html>

Explanation:

From the above code , title =”JQuery-Helpers” attribute has added with the value for all the div elements which has the class name “jQClass”.

 

How to use Selectors in JQuery

What is Selectors?

A jQuery Selector is a jquery function which uses expressions to find the given/matching elements inside the DOM object. We have already had details about selectors here. So i am going to starting how to use selectors.

Here we are going to explain much more detail with examples.

How to use Selectors?

The selectors, its the heat of jquery function to perform operation on the DOM object like event handling, Applying animation , etc.,. They fetch exact element that we mention from the HTML document. Here, let we discuss the types of selectors with examples

[su_table]
Type of selector Example
ID Selector
Selects  HTML (DOM object )elements which are match with the given selector $(‘#divCol’)
Name Selector
It select all the element which has the name of divCol inside the div. $(‘div[name=divCol]’)
Class Selector (.Class)
Selects all elements which match with the given Class. $(‘.divCol’)
Multiple Elements 
Selects the all  given type of element in the HTML document. $( “div,span,p.myClass”)
Universal (*)
 Selects all elements available in a DOM. $(‘*’)

[/su_table]

ID Selector :

It selects the element based on the given ID. The ID selector started with “#” symbol. From above example, it selects the element which has the ID attribute “divCol”.

Note : ID can’t be duplicated in a HTML document,so it will select the single Element inside the HTML Element.

Name Selector

It select all the element which matches with the given selector. From above example, $(‘div

[name=divCol]’) it will select the div element which has the name ‘divCol’

Class Selector (.Class)

As a name implies, it will select the element based on the css class name.The class selector started with ‘.’ symbol.
From above example,$(‘.divCol’) it will select all the elements which matche the class in the HTML document.

Multiple Elements

It used to select more that one element. From above example,$( “div,span,p.myClass”) it will select the all the div,span and .myclass attribute in the P tag.

Universal (*)

As name implies, it will select whole element in the document.

Features of JQuery

Main Focus of jQuery?

A jQuery is a fast and concise JavaScript Library. jQuery simplifies HTML document traversing and other operations like Ajax interaction, event handling, and animation. It is designed to write less code by using the chaining method. It has been created by John Resig in 2006 with a nice motto.

Features of JQuery:

DOM manipulation:

The jQuery made it easy to select DOM elements in our web pages.
They can traverse and able to modify the content by using the selectors(Selecting DOM Objects)

Event handling:

In simple, the event handler handles the event raised by the operation performed by the mouse, keyboard, touch, etc.,

In jQuery, it provides an elegant way to perform a wide variety of events using the DOM object like a user clicking on a button, mouse over on the div, etc.,

Lightweight :

JQuery is a very lightweight library. It will size about 19KB in size.

AJAX Support:

It supports/helps to develop a responsive and feature-rich site using AJAX technology. We can implement Ajax calls using jquery in an easier way

Cross Browser: Jquery has support cross-browser support. It will not depend on any particular browsers.

How to Use Jquery in our Project:

We can Implement jQuery in two ways.

Local Installation: we can download the jQuery library and we can include it in our project.
EG: /jquery/jquery-x.x.x.min.js

CDN: Another way we can include the jQuery library into our project is directly from Content Delivery Network (CDN).
EG : <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js”>

What is $ in Jquery?

What is $ ?

  • In jQuery, $ is an alias for jQuery. From the above statement we can able to understand, function are available without using $.
  • If you need to use another JavaScript library along side with jQuery,  then it will return control of $ back to the other library with a call to $.noConflict().
  • if noConflict() is used than the references will be restored.

Is possible to change $ symbol?

Yes, we can use any alias name instead of $, by changing the below line

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

where jQuery on the right side is the function-scoped reference.

This will be available in jquery plugin. if u want to change it to JQ then we want to change like below

// Expose jQuery to the global object
window.jQuery = window.JQ = jQuery;

after library loaded in your application you can use JQ instead of $.

 

Keep Cool Coding…