Wednesday 25 July 2012

Remove specific element from a javascript array

JavaScript Array has a splice() method which can be used to remove an element or set of elements starting from a given index. First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(2);
Then remove it with splice:

array.splice(index,1);

How to break out of jQuery.each()?

JavaScript break statement doesn't work with jQuery.each(). But the same functionality can be achieved by adding a "return false" statement within jQuery.each() once the breaking condition is reached.

$(‘ul li’).each(function(index){
  if ( $(this).hasClass(‘selected’) )
  {
    selected = index;
    return false; 
  } 
});

Html.Partial vs Html.RenderPartial

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void. The usage (using Razor syntax):

@Html.Partial("ViewName")

@{ Html.RenderPartial("ViewName");  }
The usage (using WebForms syntax):

<%: Html.Partial("ViewName") %>

<% Html.RenderPartial("ViewName"); %>
Will do exactly the same. You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial. The result will be written to the Response stream during the execution. The same is true for Html.Action and Html.RenderAction.

Asp.Net MVC partial view controller action

While you can have an action that returns a partial view, you don't need an action to render a partial view. RenderPartial takes the partial view and renders it, using the given model and view data if supplied, into the current (parent) view.
Html.RenderPartial( "Partial");
You might want an action that returns a partial view if you are using AJAX to load/reload part of a page. In that case, returning the full view is not desired since you only want to reload part of the page. In this case you can have the action just return the partial view that corresponds to that section of the page.

public ActionResult Action(...)
{ 
    return PartialView( "Partial");
}

How slow is jQuery "slow"?

jQuery animation methods like fadeIn() allows you to specify whether you want to do the animation 'slow' or 'fast'. In fact durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

How to detect IE7 with jQuery?

jQuery has a property called "$.browser.msie" which returns true when the browser is Internet Explorer. It can be combined with "$.browser.version" to decide what version of IE it is.


if ($.browser.msie  && parseInt($.browser.version, 10) === 7) {
  alert('IE7'); 
} else {
  alert('Non IE7');
}


Friday 20 July 2012

How to find event target using jQuery?

This can be done using event.target property. It returns a reference to the DOM element that initiated the event. t is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Example: Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.


<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>  
</ul>

<script>

function handler(event) {

var $target = $(event.target);

  if( $target.is("li") ) {
    $target.children().toggle();
  }
}

$("ul").click(handler).find("ul").hide();

</script>

</body>
</html>


Friday 13 July 2012

Deserializing ASP.NET AJAX JSON date using JavaScript

Modern websites are using AJAX a lot to improve customer experience by redudcing/avoiding full page reload in response to a user interaction. When AJAX is used with ASP.NET DateTime values are deserialized into below format.

"\/Date(1342137600000)\/"

Following JavaScript function can be used to deserialize it into a JavaScript Date object.

function GetDateFromJSONString(s) {
                    var d = s.replace(/\/Date\(/gi, '');
                    d = d.replace(/\)\//gi, '');
                    return  new Date(Number(d));
}

var s = "\/Date(1342137600000)\/";

alert(GetDateFromJSONString(s));

The issue with this is that JavaScript will apply the locale timezone of the client's machine while doing the deserialization which may result in a different Date value. This can be avoided by doing the deserialization bit differrently using JavaScript's toUTCString() method. This function will deserialize it into UTC Date.

var monthNames = { JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, 
JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11 }

function GetUTCDateFromJSONString(s) {
         var d = s.replace(/\/Date\(/gi, '');
         d = d.replace(/\)\//gi, '');
         var utc = new Date(Number(d)).toUTCString(); 
         //Sample value: Mon, 1 Feb 1982 00:00:00 UTC
         utc = utc.split(',')[1].substring(1).split(' ');
         utc[0] = utc[3] != '00:00:00' ? Number(utc[0]) + 1 : utc[0]; 
         return new Date(utc[2], monthNames[utc[1].toUpperCase()], utc[0]);  
}

var s = "\/Date(1342137600000)\/";

alert(GetUTCDateFromJSONString(s));



You can read more about toUTCString() method on w3schools.com. Click Here

Thursday 12 July 2012

How to center DIV in a DIV?

This can be achieved by applying below CSS to the inner div:
#outer {
  width: 100%;
}

#inner {
    width: 50%;
    margin: 0px auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing div will work. The margin: 0px auto is what does the actual centering. It can be done in a different way as well.
#outer {
  width: 100%;
  text-align: center;
}

#inner {
  display: inline-block;
}
That makes the inner div into an inline element that can be centered with text-align.

Tuesday 10 July 2012

ASP.NET MVC 3 and the @helper syntax within Razor

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code.

Key points:

  • Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional). Unlike standard C#/VB methods @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods.

  • You can invoke @helper methods just like you would a standard C# or VB method.

  • @helper method can be defined within the same view template as the code that called it. Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project. We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project.

@helper DisplayPrice(Decimal price)
{
      if(price == 0)
      {
         <span>FREE</span>
      }
      else
      {
         <text> <b>Price:<b> &pound;@(price) </text>
      }
}
Click here for more information about the @helper syntax

Import a namespace in Razor View Page?

If you want to import a namespace in your CSHTML file it can be done using @using (C#) or @imports (VB.NET) statement.

C# Example

@using System.Configuration;