Category Archives: JQUERY

Binding & posting to a Dictionary in MVC 3 using jQuery

Binding, posting to a Dictionary in MVC 3 using jQuery ajax

In this post we are going to discuss how to post data to a Dictionary using jQuery ajax. Lets have a simple model from the previous post and pass value to the action method as dictionary of the model we get the following controller method.

public ActionResult Binding_posting_to_a_dictionary_using_ajax(Dictionary<string, UserModel> userList)
    return PartialView("Success");

To work with dictionary the default model binder will accept the data in a particular format. If we consider key of the first element of the dictionary as firstkey then we have to give the name of the input parameter as [0].value.ModelPropertyName. So, for the first item we can give the names like-

<input name="[0].key" value="firstkey" type="hidden">
<input name="[0].value.FirstName" value="" type="text">
<input name="[0].value.LastName" value="" type="text">
<input name="[0].value.Age" value="" type="text">

If we see the above code block, we can see there is a hidden field for maintaining the key of the dictionary element and the value of the hidden filed is nothing but the key of the dictionary element

<div class="data">
        First User</h4>
    <input type="hidden" name="[0].key" value="first" />
    First Name: @Html.TextBox("[0].value.FirstName")
    Last Name: @Html.TextBox("[0].value.LastName")
    Age: @Html.TextBox("[0].value.Age")
<div class="data">
        Second User</h4>
    <input type="hidden" name="[1].key" value="second" />
    First Name: @Html.TextBox("[1].value.FirstName")
    Last Name: @Html.TextBox("[1].value.LastName")
    Age: @Html.TextBox("[1].value.Age")
<div class="data">
        Third User</h4>
    <input type="hidden" name="[2].key" value="third" />
    First Name: @Html.TextBox("[2].value.FirstName")
    Last Name: @Html.TextBox("[2].value.LastName")
    Age: @Html.TextBox("[2].value.Age")
<input type="button" id="submitData" value="Submit data" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#submitData").click(function () {
            var datatopost = new Object();
            $(".data").each(function (i, item) {
                datatopost[$(item).find("input[name*=FirstName]").attr("name")] = $(item).find("input[name*=FirstName]").val();
                datatopost[$(item).find("input[name*=LastName]").attr("name")] = $(item).find("input[name*=LastName]").val();
                datatopost[$(item).find("input[name*=Age]").attr("name")] = $(item).find("input[name*=Age]").val();
                datatopost[$(item).find("input[name*=key]").attr("name")] = $(item).find("input[name*=key]").val();
                url: '@Url.Action("Binding_posting_to_a_dictionary_using_ajax")',
                type: 'POST',
                traditional: true,
                data: datatopost,
                dataType: "json",
                success: function (response) {
                error: function (xhr) {


<httpCookies domain="String" 
             requireSSL="true|false" />

The following default httpCookies element is not explicitly configured in the machine configuration file or in the root Web.config file, but is the default configuration returned by an application in the .NET Framework version 2.0.

 Internet Explorer added support in Internet Explorer 6 SP1 for a cookie property called HttpOnlyCookies that can help mitigate cross-site scripting threats that result in stolen cookies. When a cookie that has HttpOnlyCookies set to true is received by a compliant browser, it is inaccessible to client-side script. For more information on possible attacks and how this cookie property can help mitigate them, please see Mitigating Cross-Site Scripting with HTTP-Only Cookies tutorial on MSDN.
<httpCookies httpOnlyCookies="false" 
  domain="" />

advantages and disadvantages of using a content delivery network (CDN)

What are the advantages and disadvantages of using a content delivery network (CDN)?

  • The disadvantages may be that it costs money, and it adds a bit of complexity to your deployment procedures.
  • The main advantage is an increase in the speed with which the content is delivered to the users.

When to use a CDN?

  • It will be most effective when you have a popular public website with some type of static content (images, scripts, CSS, etc.).

Is a CDN a performance booster?

  • In general, yes. When a specific request is made by a user, the server closest to that user (in terms of the minimum number of nodes between the server and the user) is dynamically determined. This optimizes the speed with which the content is delivered to that user.


  • It increases the parallelism available.
    (Most browsers will only download 3 or 4 files at a time from any given site.)
  • It increases the chance that there will be a cache-hit.
    (As more sites follow this practice, more users already have the file ready.)
  • It ensures that the payload will be as small as possible.
    (Google can pre-compress the file in a wide array of formats (like GZIP or DEFLATE). This makes the time-to-download very small, because it is super compressed and it isn’t compressed on the fly.)
  • It reduces the amount of bandwidth used by your server.
    (Google is basically offering free bandwidth.)
  • It ensures that the user will get a geographically close response.
    (Google has servers all over the world, further decreasing the latency.)
  • (Optional) They will automatically keep your scripts up to date.
    (If you like to “fly by the seat of your pants,” you can always use the latest version of any script that they offer. These could fix security holes, but generally just break your stuff.)


Protection against SQL injection

Protection against SQL injection needs to take place on server side, regardless where the incoming call comes from.

Javascript-based sanitation methods are always useless because Javascript runs on client side, and therefore can be forged.

This also applies for AJAX calls: The client doesn’t need to turn JavaScript off; they just need to manipulate the Javascript code they download from your site to fake validation.

bundle files in specific order


internal class AsIsBundleOrderer : IBundleOrderer
    public virtual IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
        return files;

internal static class BundleExtensions
    public static Bundle ForceOrdered(this Bundle sb)
        sb.Orderer = new AsIsBundleOrderer();
        return sb;


    bundles.Add(new ScriptBundle("~/content/js/site")

I like using fluent syntax but it also works with a single method call and all the scripts passed as parameters.


Basically, jQuery is a great tool for you to manipulate and control DOM elements. If you only focus on DOM elements and no Data CRUD, like building a website not web application, jQuery is the one of the top tools. (You can use AngularJS for this purpose as well.)

AngularJS is a framework. It has following features

  1. Two way data binding
  2. MVW pattern (MVC-ish)
  3. Template
  4. Custom-directive (reusable components, custom markup)
  5. REST-friendly
  6. Deep Linking (set up a link for any dynamic page)
  7. Form Validation
  8. Server Communication
  9. Localization
  10. Dependency injection
  11. Full testing environment (both unit, e2e)

    AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it’s not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

    JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Using Bootstrap Tooltips to display jQuery Validation error messages

Using Bootstrap Tooltips to display jQuery Validation error messages

I love jQuery Validation. I was recently putting together a screen which had a lot of different bits of validation going on. And the default jQuery Validation approach of displaying the validation messages next to the element being validated wasn’t working for me. That is to say, because of the amount of elements on the form, the appearance of validation messages was really making a mess of the presentation. So what to do?

<!DOCTYPE 2014-01-03_1355html>
<html lang=”en”>
<meta charset=”utf-8″ />
<link href=”//” rel=”stylesheet”>
form { padding: 10px; }
.error { border: 1px solid #b94a48!important; background-color: #fee!important; }
<div class=”row”>
<label for=”RequiredDateDemo”>A date is required (eg “15 June 2012”):</label>
data-msg-date=”The field RequiredDateDemo must be a date.”
data-msg-required=”The RequiredDateDemo field is required.”
id=”RequiredDateDemo” name=”RequiredDateDemo” type=”text” value=”” />
<div class=”row”>
<label for=”StringLengthAndRequiredDemo”>A string is required between 5 and 10 characters long:</label>
data-msg-maxlength=”The field StringLengthAndRequiredDemo must be a string with a minimum length of 5 and a maximum length of 10.”
data-msg-minlength=”The field StringLengthAndRequiredDemo must be a string with a minimum length of 5 and a maximum length of 10.”
data-msg-required=”The StringLengthAndRequiredDemo field is required.”
id=”StringLengthAndRequiredDemo” name=”StringLengthAndRequiredDemo” type=”text” value=”” />
<div class=”row”>
<label for=”RangeAndNumberDemo”>Must be a number between -20 and 40:</label>
data-msg-number=”The field RangeAndNumberDemo must be a number.”
data-msg-range=”The field RangeAndNumberDemo must be between -20 and 40.”
id=”RangeAndNumberDemo” name=”RangeAndNumberDemo” type=”text” value=”-21″ />
<div class=”row”>
<label for=”RangeAndNumberDemo”>An option must be selected:</label>
data-msg-required=”The DropDownRequiredDemo field is required.”
id=”DropDownRequiredDemo” name=”DropDownRequiredDemo”>
<option value=””>Please select</option>
<option value=”An Option”>An Option</option>
<div class=”row”>
<button type=”submit”>Validate</button>
<script src=”//” type=”text/javascript”></script>
<script src=”//” type=”text/javascript”></script>
<script src=”//”></script>
<script type=”text/javascript”>
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function (index, element) {
var $element = $(element);
$“title”, “”) // Clear the title – there is no error associated anymore
// Create new tooltips for invalid elements
$.each(errorList, function (index, error) {
var $element = $(error.element);
$element.tooltip(“destroy”) // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data(“title”, error.message)
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
submitHandler: function(form) {
alert(“This is a valid form!”);