Thursday, March 13, 2014

Get page name from URL, using Javascript

You can use following function to retrieve the current page name from the URL.

 function getCurentFileName() {
             var pagePathName = window.location.pathname;
             return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);

Thursday, January 30, 2014

Redirect to .aspx webform within ASP.NET MVC application

public class PivotalController : Controller
        public RedirectResult Index()
            return Redirect("/pages/PivotalWebForm.aspx");


Tuesday, January 28, 2014

How to solve XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin error in ASP.NET MVC 4

This error may occur when you try to communicate between different domain using AJAX calls. To solve the issue we need set up the WEB API to return correct headers.

Create a class called CrossDomainActionFilter inherited by ActionFilterAttribute.

public class CrossDomainActionFilter : ActionFilterAttribute
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            bool needCrossDomain = true;

            if (needCrossDomain)
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");


[AcceptVerbs("GET", "POST")]
    public object GetTest()
         rep = new ChatRepository();
        chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);

        System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
            Data = box,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet

        return jsonResult.Data;

Tuesday, January 21, 2014

How to validate dd/MM/yyyy date format in ASP.NET MVC client validations.

The problem is JQUERY validation does not consider the culture when performing the validation. So that, it will show you "Invalid date format" error message whenever you try to submit a form with a date field, which has the format of dd/MM/yyyy.

To fix the issue we can override the default validation behavior by including JQUERY Globalization plugin.

Right click on the application on in Visual Studio and select Manage NuGet Packages.

Then type globalize on search text box and install the package, which appears on the search results.

Finally, add the below script before the body closing tag on your page.

    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/globalize/globalize.js"></script>
    <script src="~/Scripts/globalize/cultures/globalize.culture.en-GB.js"></script>

        $(document).ready(function () {
            $.culture = Globalize.culture("en-GB");
            $ = function (value, element) {
                //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale
                //and despite displaying in the specified format.

                return this.optional(element)
                    || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
                    || Globalize.parseDate(value, "yyyy-mm-dd");

Sunday, January 19, 2014

Allow only decimal or integer numbers in a textbox using JQUERY


<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed  (With Decimal Point) </div>  
    <br/>   <br/>   <br/>
<input type="text" name="numeric" class='allownumericwithoutdecimal'>
<div>Numeric values only allowed  (Without Decimal Point) </div>

Below code will allow user to enter only decimal numbers:

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
            //this.value = this.value.replace(/[^0-9\.]/g,'');
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {

Below code will allow user to enter only integer numbers:

$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {  
           $(this).val($(this).val().replace(/[^\d].+/, ""));
            if ((event.which < 48 || event.which > 57)) {

Tuesday, December 31, 2013

How to enable Client Side Validation for Kendo UI

Recently I was struggling with using Jquery validation in ASP.NET MVC 4 application which used Kendo UI. Except the kendo DropDownLists in a particular view, every other control fired client validations. So it had to be a problem with Kendo libraries. Finally, I added below code snippet and it started working.

Kendo DropDown:

@(Html.Kendo().DropDownListFor(m => m.SiteID)
                            .OptionLabel("Select Below...")
                            .DataSource(ds =>
                                ds.Read("ToolbarTemplate_Categories", "EnterNewDocumentVendor");

Jquery Code:


    $(document).ready(function () {

            ignore: ""


Following link would be useful for newer versions of Jquery.

Tuesday, November 19, 2013

Telerik Reports for ASP.NET MVC 4 Caching issue.

I recently used Telerik reports, and i got into a problem where report viewer cached the previous versions other than refreshing the report.

I followed the sample in below link from telerik in order to generate my report.

below is the code from my report viewer.

        .ReportSource(new TypeReportSource() { TypeName = "MvcReportApplication.MyReport.Report5, MvcReportApplication" })

To disable the report viewer caching just change PersistSession(true) to PersistSession(false) and you are good to go.

Tuesday, October 1, 2013

Create/Read JavaScript Cookie

Following two methods can be used to create a cookie on the client browser and to read the value of the cookie.

Create Cookie:

name of the cookie, value need to be stored in the cookie and the number of days for cookie expiration are the parameters to be passed when calling the method.

function createCookie(name, value, days) {
                            if (days) {
                                var date = new Date();
                                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                                var expires = "; expires=" + date.toGMTString();
                            else var expires = "";
                            document.cookie = name + "=" + value + expires + "; path=/";

Read Cookie:

  function readCookie(name) {
                    var nameEQ = name + "=";
                    var ca = document.cookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                    return null;

Thursday, September 26, 2013

How to Read MS Word Document Content using Office Interoperability Service Assemblies

Below code will read the content of a Microsoft Word document and return the text in a string variable.

public string GetText()
                string Referees = string.Empty;
                string totaltext = "";
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

                object miss = System.Reflection.Missing.Value;
                object path = Server.MapPath("~/Content/Documents/CV March 2013 Peter Corbitt.docx");
                object readOnly = true;
                Microsoft.Office.Interop.Word.Document docsw = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                    for (int i = 0; i < docsw.Paragraphs.Count; i++)
                        totaltext += " \r\n " + docsw.Paragraphs[i + 1].Range.Text.ToString();

                catch (Exception ex)
                    throw ex;

                return totaltext;

Monday, September 2, 2013

How to use ajaxError

When ever an error occurs in an ajax call it fires ajaxError function. By examining the error details you'll be able to get an idea about the occurred error.

$( document ).ajaxError(function(event, xhr, options, exc) {
  alert('Couldn\'t load ' + options.url + ' because (' +
            xhr.status + ' - ' + xhr.statusText + ') ' + exc.message);