Share on facebook – chrome extension

Long back I wrote a post about how to create a chrome extension. This post is about creating an extension which will help you to share current page URL on facebook. You can follow the same steps in the previous post except few changes in the background.js file. And facebook uses a URL like this to accept URL – http://www.facebook.com/sharer.php?u=[URL to share].

chrome.contextMenus.create({
    "title": "Share this URL on Facebook",
    "contexts": ["page", "link"],
    "onclick": function() {
		chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
			Popup(tabs[0].url);
		});
    }
});

function Popup(url) {
  chrome.windows.create({'url': 'http://www.facebook.com/sharer.php?u=' + url, 'type': 'popup'}, function(window) {});
}

And here is the screenshot of the extension running on my chrome browser.

Share on facebook from chrome extension

Share on facebook from chrome extension

You can find the source code on GitHub – https://github.com/anuraj/ShareOnFb

Happy Programming :)

How to integrate JQuery UI Datepicker in MVC

This post is about integrating JQuery UI DatePicker in MVC 4. First you need to modify the _layout.cshtml. Because by defualt, it won’t include required references for JQuery UI. You need to include both CSS and JS for JQuery UI references. So the modified _layout.cshtml will look like this.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @RenderSection("scripts", required: false)
</body>
</html>

And in the CSHTML where you want to include the JQuery Date Picker, include the following snippet.

$(function () {
    $("#JoiningDate").datepicker();
});

Clicking on the textbox will popup calender like this.

JQuery UI DateTime Picker in MVC

JQuery UI DateTime Picker in MVC

It works perfectly, until validations come in to the play :) As my application is targeted to India / UK customers, I have added a formatting to DatePicker like this.

$(function () {
    $("#JoiningDate").datepicker({
        dateFormat: 'dd/mm/yy'
    });
});

But MVC validator controls didn’t recognize the textbox value as a valid date time.

JQuery UI DateTime Picker in MVC - Date Validation fails

JQuery UI DateTime Picker in MVC – Date Validation fails

To resolve this issue, you need to override the date validation behaviour of JQuery validation library. You can do this by adding following snippet.

$(function () {
    $.validator.addMethod("date", function (value, element) {
        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });
});

Also you need to add the Display Format attribute to the Model property.

[Required]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
    ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }

Happy Programming :)

Loading partial view on Ajax.Actionlink click

While working on an MVC project, I had to create few partial views and load them dynamically using Ajax. Here is the code snippet for the same.

Controller method

public ActionResult ShowMenu()
{
    return PartialView("_SimpleMenu");
}

In this I am returning the Partial View in the controller method. And here is the Razor code.

<div id="MenuContainer">
</div>
@Ajax.ActionLink("Show menu", "ShowMenu", "Home", new AjaxOptions()
{
    UpdateTargetId = "MenuContainer",
    InsertionMode = InsertionMode.Replace
})

In this I am specifying the controller action method and the DIV which will be replaced by the Partial View.

Happy Coding.

How to implement file type validation using JQuery validation library

Recently I worked on an MVC project, which supports file uploads, only DOC and PDF files. And here is the code snippet which helps to restrict file types using JQuery validation library.

$(function () {
    $("#SampleForm").validate({
        rules: {
            txtName: { required: true },
            txtFile: { required: true, accept: 'docx|pdf' }
        },
        messages: {
            txtName: { required: "Please enter your firstname" },
            txtFile: {
                required: "Please select a file",
                accept: "Please select a valid file type"
            }
        },
        submitHandler: function (form) {
            var $form = $(form);
            $form.submit();
        }
    });
});

For file type format validation you require one more library, additional-methods.js, this library contains additional methods validation. You can find all the required libraries for this code in Microsoft CDN.

And here is the simple snippet for the same without JQuery validation dependency.

var extn = $('#txtFile').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['docx','pdf') == -1) {
    alert('invalid extension!');
}

Links

  • JQuery : http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js
  • JQuery Validation: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.js
  • Validation Additional methods: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/additional-methods.js

Happy Programming :)