MVC5 Ajax form is not updating DIV but replacing the whole page instead

Standard

While working on MVC5 application, I faced this issue, I was using Ajax.BeginForm() and from controller, I was returning content result. But instead of updating the DIV, the content was opened in new Tab. Initially I thought it was due to some javascript error, but it was not working with Ajax.ActionLink also. Later I found it was due to missing “Microsoft.jQuery.Unobtrusive.Ajax” package. You can install this via NuGet.

NuGet package - Microsoft.jQuery.Unobtrusive.Ajax

NuGet package – Microsoft.jQuery.Unobtrusive.Ajax

And include it in the BundleConfig.cs.

bundles.Add(new ScriptBundle("~/bundles/jqueryunobtrusive").Include(
            "~/Scripts/jquery.unobtrusive*"));

And include the jqueryunobtrusive in _layout.cshtml file.

@Scripts.Render("~/bundles/jqueryunobtrusive")

It will resolve this issue.

Happy Programming :)

Load ASP.NET MVC partial views on link click

Standard

Some one asked me how we can load partial views on link click. Here is the snippet for the same.

Long version – Using JQuery

<script type="text/javascript">
$("#loadPartialView").click(function () {
    $.get('@Url.Action("LoadPartialView","Home")', {}, function (response) {
        $("#Display").html(response);
    });
});
</script>

And here is the small version using Ajax.ActionLink

@Ajax.ActionLink("Load Partial View", "LoadPartialView", "Home",
    new AjaxOptions() { UpdateTargetId = "Display" })

In the page, you need to add a DIV with Id attribute which got a value “Display”, partial view will be loaded to this DIV.

And here is the controller action

public ActionResult LoadPartialView()
{
    return PartialView("_PartialView");
}

Happy Programming :)

Share on facebook – chrome extension

Standard

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

Standard

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 :)