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.

[HttpPost]
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">
    <h4>
        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>
<div class="data">
    <h4>
        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>
<div class="data">
    <h4>
        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")
</div>
<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();
            });
            $.ajax({
                url: '@Url.Action("Binding_posting_to_a_dictionary_using_ajax")',
                type: 'POST',
                traditional: true,
                data: datatopost,
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                error: function (xhr) {
                    alert(xhr);
 
                }
            });
        });
    });
</script>

httpOnlyCookies

<httpCookies domain="String" 
             httpOnlyCookies="true|false" 
             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" 
  requireSSL="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.

Advantages

  • 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;
    }
}

Usage:

    bundles.Add(new ScriptBundle("~/content/js/site")
        .Include("~/content/scripts/jquery-{version}.js")
        .Include("~/content/scripts/bootstrap-{version}.js")
        .Include("~/content/scripts/jquery.validate-{version}")
        .ForceOrdered());

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

ANGULARJS AND/VS JQUERY

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”>
<head>
<meta charset=”utf-8″ />
<link href=”//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css” rel=”stylesheet”>
<style>
form { padding: 10px; }
.error { border: 1px solid #b94a48!important; background-color: #fee!important; }
</style>
</head>
<body>
<form>
<div class=”row”>
<label for=”RequiredDateDemo”>A date is required (eg “15 June 2012”):</label>
<input
data-msg-date=”The field RequiredDateDemo must be a date.”
data-msg-required=”The RequiredDateDemo field is required.”
data-rule-date=”true”
data-rule-required=”true”
id=”RequiredDateDemo” name=”RequiredDateDemo” type=”text” value=”” />
</div>
<div class=”row”>
<label for=”StringLengthAndRequiredDemo”>A string is required between 5 and 10 characters long:</label>
<input
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.”
data-rule-maxlength=”10″
data-rule-minlength=”5″
data-rule-required=”true”
id=”StringLengthAndRequiredDemo” name=”StringLengthAndRequiredDemo” type=”text” value=”” />
</div>
<div class=”row”>
<label for=”RangeAndNumberDemo”>Must be a number between -20 and 40:</label>
<input
data-msg-number=”The field RangeAndNumberDemo must be a number.”
data-msg-range=”The field RangeAndNumberDemo must be between -20 and 40.”
data-rule-number=”true”
data-rule-range=”[-20,40]”
id=”RangeAndNumberDemo” name=”RangeAndNumberDemo” type=”text” value=”-21″ />
</div>
<div class=”row”>
<label for=”RangeAndNumberDemo”>An option must be selected:</label>
<select
data-msg-required=”The DropDownRequiredDemo field is required.”
data-rule-required=”true”
id=”DropDownRequiredDemo” name=”DropDownRequiredDemo”>
<option value=””>Please select</option>
<option value=”An Option”>An Option</option>
</select>
</div>
<div class=”row”>
<button type=”submit”>Validate</button>
</div>
</form>
<script src=”//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js” type=”text/javascript”></script>
<script src=”//ajax.aspnetcdn.com/ajax/jQuery.validate/1.11.1/jquery.validate.js” type=”text/javascript”></script>
<script src=”//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js”></script>
<script type=”text/javascript”>
$(“form”).validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function (index, element) {
var $element = $(element);
$element.data(“title”, “”) // Clear the title – there is no error associated anymore
.removeClass(“error”)
.tooltip(“destroy”);
});
// 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)
.addClass(“error”)
.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!”);
}
});
</script>
</body>
</html>