Tuesday, December 24, 2013

MaxJsonLength exception

MaxJsonLength exception in ASP.NET MVC4 during JavascriptSerializer:

Code:
public ActionResult Index(){
    var data = null  //give some large data e.g big list of values
    var resultData = Json(data, JsonRequestBehavior.AllowGet);
    resultData.MaxJsonLength = Int32.MaxValue;
    return resultData;
}

Note: Then web.config setting is ignored by the default JsonResult implementation. So we might need to implement a custom Json Result or we can use the above code.

Friday, September 6, 2013

Enable Compatibility mode in IE

Introduction
As there are new releases of IE(Internet Explorer) coming out regularly with new features and functionalities, it is not required for legacy page/site to support latest version of the browser. So, for this reason compatibility mode is been introduced in IE8 onwards.
Problem
I have an ASP.NET MVC web application, I want it to run in IE8 or IE9 compatiblity mode in IE10 as our client uses only IE8 or IE9 and we have IE10 in our work stations. Lets see how can we acheive this.
Solution
We can achieve this by setting the value of the compatiblity mode.
Web page can specify compatibility mode either by using META tag or by setting the http header, note that META tag will take precedence over http header when both are present.

Sol 1: META Tag- place the following code in head element of web page(html page)
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9"/>
it is not only applicable for IE but also for other browsers like chrome
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, chrome=1"/>
Important to Note: META tag should be placed in head section before any script or css tag.

Sol 2: HTTP Header- We can configure our server to send a HTTP Header along with each page i.e send "X-UA-Compatibility: IE=8" HTTP header
Now, how do we achieve the same in ASP.NET MVC application?
Add the following code snippet in web.config file
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <clear/>
            <add name="X-UA-Compatible" value="IE=8"/>
        </customHeaders>
    </httpProtocol>
<system.webServer>
Important to Note:
  • system.webServer tag will only be effective if your MVC3 is to run on IIS7 or later
  • If you find your <meta> tag is overridden by IE's intranet settings, this webServer setting will override the compatibility.
For more details browser compatibility mode click here.

Monday, August 12, 2013

Get unique/distinct values from an array using JQuery $.grep and $.inArray

Consider an example of getting unique elments from an array a = [1,1,2,3,8,2]

Array.prototype.unique = function(){
    var array = this;
    return array.filter(function(ele, index, arr){
        return index == arr.indexOf(ele);
    });
}
and in our Javascript,

var array = [1,1,2,3,8,2];
var uniqueElments = arrray.unique();

//Output will be 1,2,3,8
But the issue is few of the older version browsers including IE7 that doesn't support some array features - such as indexOf or filter, so we can use jquery functionalities like:

  •     use $.grep instead of Array.filter
    • The $.grep() method removes items from an array as necessary so that all remaining        items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
  • use $.inArray instead of Array.indexOf
    • The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
Now here's how the changed code would look like:

Array.prototype.unique = function(){
    var array = this;
    return $.grep(array, function(ele, index){
            return $.inArray(ele, array) === index;
    });
}
References:
$.grep
$.inArray

Friday, July 26, 2013

ASP.NET MVC Custom HTML Helpers (C#)

In this article we will understand the different ways of creating custom helper method in ASP.NET MVC4 application. Though we have built-in html helpers like Html.ActionLink(), Html.TextBox() and many more, some times we may need to have custom helper methods for example Image or a block of html controls which is commonly used across the application like Address fields.


Custom HTML Helpers make it easier to generate view content. We can create custom helpers in three ways:

1. with Static Methods
2. with Extension Methods
3. with @helper in the razor view.

Let's understand how to implement the same.

1. Static Methods:


In this approach we will create a static method and use that method in the view, here its is ImageStatic method which will return HtmlString.


CustomHelper.cs:
namespace HelperApplication.Helpers
{
    public static class CustomHelpers
    {
        //Static method
        public static IHtmlString ImageStatic(string src, string alt = "Image", int width = 50, int height = 50)
        {
            var value = String.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>", src, alt, width, height);
            return new HtmlString(value);
        }
        //Extension method
        public static IHtmlString ImageExtension(this HtmlHelper helper, string src, string alt = "image", int width = 50, int height = 50)
        {
            var value = String.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>", src, alt, width, height);
            return new HtmlString(value);
        }
    }
}

src- image source (path)
alt- alternative text if image could not be loaded, and it is assigned a default value "Image". When no values is passed to this parameter it will take the default value "Image".
width & height- width and height of the image these parameters are also assigned a default value 50

Using the ImageStatic html helper method in view..
Index.cshtml:

@using HelperApplication.Helpers
<div>
     <span>ImageTag with default values for alt, width, height</span>     
     @CustomHelpers.ImageTag("../../images/image.png")
</div>
<div>
     <span>ImageTag with width=100 and height=100</span>     
     @CustomHelpers.ImageStatic("../../images/image.png","Image With alt",100,100)
</div>

The above code will render the images one with default dimensions(i.e width and height) and another one with given dimension (i.e width=100 and height=100)

2. Extension Methods:


This is another approach to create custom html helpers, here we will extend the functionality of the HtmlHelper class.

In the CustomHelper.cs class we have created another method called ImageExtension. We can see this HtmlHelper helper parameter, this implies that ImageExtension method extends functionality of HtmlHelper class. Thus, we can use this method just like other helper methods (Html.ActionLink() similarly Html.ImageExtension).

Note: To make our method accessible like other built-in helper methods we have to add namespace to webconfig file <add namespace="HelperApplication.Helpers"/> in ~/Views/web.config not in ~/web.config

Index.cshtml:
<div>
    <span>ImageTag with default values for alt, width, height</span>
     @Html.ImageExtension("../../images/image.png")
</div>
<div>
     <span>ImageTag with width=100 and height=100</span>
     @Html.ImageExtension("../../images/image.png","Image With alt",100,100)
</div>

3. @helper :