Archive for the ‘Jquery in Asp.Net’ Category

Dynamically Creating and Showing Bootstrap Modal

October 18, 2015 Leave a comment

Yes I do agree Bootstrap is very cool. Well at-least for a developer you don’t have to mess with a lot of css figuring out responsiveness mobile friendly and a cool design. There may be a lot of other reasons for you to like it but personally I like it because it is now a fully matured framework and also you get a very active community for help.

And recently I was using bootstrap’s Modal quite heavily. So I had to write a lot code in javascript and during the process also wrote this small piece of code to create and show bootstrap modal at run-time in javascript having dynamic title, body and buttons. Thought to share here if anyone needs, though most of us may have already in our code repositories but still no harm in sharing right :).
OK, here are some details about these functions;

 BstrapModal function (title, body, buttons) 

BstrapModal class has a single constructor which takes these three parameters title, body and buttons.

  • Title:Title of the Modal. It can be both html or simple string.
  • Body: Body of the Modal. It can also be html or string.
  • Buttons: Buttons in the footer of the Modal. It is an array of the Button Object. Button object should have Value, Css and Callback function of the button. Value is just the display text of the button while Callback function would be executed on clicking the button. e.g. a button object would look like this
     {Value:"CLOSE", Css:"btn-danger", 
    Callback:function(event){/*Close button click logic*/ }} 

    BstrapModal.Close will close the modal and delete it from document.

    You can extend this class with your requirements. e.g. For different bootstrap button types you can create an enum and put in the constructor. Or you can extend show function so it can get the modal type like large or small etc.

    var BstrapModal = function (title, body, buttons) {
        var title = title || "Lorem Ipsum History", body = body || "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.", buttons = buttons || [{ Value: "CLOSE", Css: "btn-primary", Callback: function (event) { BstrapModal.Close(); } }];
        var GetModalStructure = function () {
            var that = this;
            that.Id = BstrapModal.Id = Math.random();
            var buttonshtml = "";
            for (var i = 0; i < buttons.length; i++) {
                buttonshtml += "<button type='button' class='btn " + (buttons[i].Css||"") + "' name='btn" + that.Id + "'>" + (buttons[i].Value||"CLOSE") + "</button>";
            return "<div class='modal fade' name='dynamiccustommodal' id='" + that.Id + "' tabindex='-1' role='dialog' data-backdrop='static' data-keyboard='false' aria-labelledby='" + that.Id + "Label'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><button type='button' class='close modal-white-close' onclick='BstrapModal.Close()'><span aria-hidden='true'>&times;</span></button><h4 class='modal-title'>" + title + "</h4></div><div class='modal-body'><div class='row'><div class='col-xs-12 col-md-12 col-sm-12 col-lg-12'>" + body + "</div></div></div><div class='modal-footer bg-default'><div class='col-xs-12 col-sm-12 col-lg-12'>" + buttonshtml + "</div></div></div></div></div>";
        BstrapModal.Delete = function () {
            var modals = document.getElementsByName("dynamiccustommodal");
            if (modals.length > 0) document.body.removeChild(modals[0]);
        BstrapModal.Close = function () {
        this.Show = function () {
            var btns = document.querySelectorAll("button[name='btn" + BstrapModal.Id + "']");
            for (var i = 0; i < btns.length; i++) {
                btns[i].addEventListener("click", buttons[i].Callback || BstrapModal.Close);

    You can use this as;

        new BstrapModal().Show();

    This will show you the below modal, as we didn’t pass any title, body and buttons array, so it will use all default values;

    I used Bootstrap v3.3.5 as you can see in this screen-cast from my project;

WCF RESTful service hosting on IIS6 and consuming by jQuery

July 18, 2014 Leave a comment

Couple of days ago I needed to deploy a WCF RESTfull service on IIS6. Before then I never deployed RESTfull service on IIS6 so it came up with quite configurations for me. While I was deploying this web service on IIS6, I as usual goggled for some configuration related help, although I found, but most of the stuff were scattered. I mean I didn’t find all in a single post or a blog. So I thought why couldn’t do it.

In this post I developed a WCF RESTfull web service from scratch to hosting on web server and consuming by jQuery ajax. Here is the service contract. You’ll find UriTemplate with both with parameters and without parameter.

 /// <PostedOn></PostedOn>
    /// <PostedBy>Muhammad Hussain</PostedBy>
    [ServiceContract(Name = "DeepASPService", Namespace = "")]    
    interface IDeepASPService
        /// <summary>
        /// Returns all articles from the blog.
        /// </summary>        
        /// <returns></returns>
        [WebGet(UriTemplate = "/GetArticles?blogName={blogName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        
        List<Article> GetAllArticles(string blogName);

        [WebGet(UriTemplate = "/GetTagArticles?tagName={tagName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        List<Article> GetArticlesByTagName(string tagName);

        [WebGet(UriTemplate = "/GetArticle?Id={Id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        Article GetArticleById(string Id);

        [WebGet(UriTemplate = "/SaveArticle?authenticationToken={authenticationToken}&amp;title={title}&amp;body={body}&amp;submittedBy={submittedBy}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        bool SaveArticle(string authenticationToken, string title, string body, string submittedBy);

Here is the Service implementing above contract. Most of the operations are only defined and not fully implemented as it didn’t need for this post. GetArticles operation returns a generic list in json format.

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DeepASPService : IDeepASPService
        public List<Article> GetAllArticles(string blogName)
            return new List<Article>()
                new Article { Id = Guid.NewGuid(), Name=blogName, Title = "WCF RESTfull web service.", Body = "Html body.", Comments=new List<Comment>()
                    new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = null }
                new Article { Id = Guid.NewGuid(), Name=blogName,Title = "WCF RESTfull web service deploying on IIS 6.", Body = "Html body.", Comments=new List<Comment>()
                        new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = new List<Comment> ()
                            new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies =null } 

        public List<Article> GetArticlesByTagName(string tagName)
            throw new NotImplementedException();

        public Article GetArticleById(string Id)
            throw new NotImplementedException();

        public bool SaveArticle(string authenticationToken, string title, string body, string submittedBy)
            if (AuthenticateRequest(authenticationToken))
                //save article 
            return true;

        private bool AuthenticateRequest(string authenticationToken)
            //authentication code
            return true;

In this sample application there are only two data contracts but you can have as many data contracts as you need.

    public class Article
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public List<Comment> Comments { get; set; }        
    public class Comment
        public Guid Id { get; set; }

        public string DisplayName { get; set; }

        public string Body { get; set; }

        public DateTime CommentedOn { get; set; }

        public string Email { get; set; }

        public List<Comment> Replies { get; set; }


<%@ ServiceHost Language="C#" Debug="true" Service="Namespace.ServiceName" CodeBehind="ServiceName.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>



    <compilation debug="true" targetFramework="4.0" />
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      <service name="Namespace.ServiceName" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="Namespace.ServiceInterface"
        <behavior name="ServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="True"/>
        <behavior name="webHttp">
    <modules runAllManagedModulesForAllRequests="true"/>

Now we will host this service on IIS. So here is the step by step procedure;

1-Right click on website go to New

2-Click Create virtual directory(in this sample code I created a virutal directory in an existing website)

3- A wizard screen will come up like;
















4-Click Next

5-In Alias textbox give any name for your service e.g. TestRESTfullService

6-Next and browse the path where your service is e.g. wwwroot\RESTfullWCFService




Now although you have successfully deployed your service on IIS but hereafter configurations are required to run it properly.

1-Right click on the new virtual directory you created(e.g. TestRESTfullService)

2-Go to properties

3-By default this virtual directory will be shown as a website(globe logo will appear before it) so you need to convert this into an application.

4-Click on Create application button as showing at #1 in the below picture. After creating application your service icon will change from globe to gear.


















figure 2

5-Change execute permissions from None to Scripts only like the process 2 in the above picture

6- Click on Configuration button and you’ll see this screen;











7-Click on Insert and you’ll see a small screen like this;






8-Click on Browse and select aspnet_isapi.dll from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll. If you don’t find v4.0.30319 folder and it means you don’t have dotnet framework 4 full version. So you’ll have to download it from microsoft website and install it. After installation complete you’ll find this so then select it.

9- DO NOT FORGET to uncheck “Verify that file exists” checkbox from the above screen.

10- Now click on Directory Security tab from figure 2.

11- In this Authentication Methods screen you will uncheck “Integrated windows authentication” checkbox.

12- Click OK.

13-Now go to ASP.Net tab from figure 2 and select ASP.Net version : 4.0.30313. (Sometimes a message will appear when version is changed so just press OK).

14- Now restart your IIS. It will lose all sessions of websites hosted on this server so be cautious, its better to do at night time.

14-That’s all you needed.You’ve done it !

Your WCF RESTfull service must be running

Now its time to consume your service. Here we will consume using jQuery ajax like;

function GetAllArticles() {
            var url = "/TestRESTfullService/ServiceName.svc/GetArticles?blogName=deepasp"
            $(function() {
                    type: "GET"
                    url: url,
                    async: true,
                    dataType: "json"
                    success: function(articles) {
                        if (articles != null) {
                            document.getElementById("response").innerHTML = ConvertObjecToHtml(articles);
                            document.getElementById("response").innerHTML ="No articles published yet on this blog."
                    error: function(e) {
                        alert("Error occured while processing service request" + e.responseText);

Here download the source code;

Uses of Jquery Filter Selector

December 4, 2013 Leave a comment

Jquery Filter selector becomes very handy for a geek who’s found of lambda function in LINQ. Here are some scenarios where we can easily use filter selector. Its very useful for a complex filter.
Some of the scenarios are;

  1. Dynamically setting the selected option of a dropdownlist
      $('#dropdownlistId option').filter(function() {
    return $.trim( $(this).text() ) == "Value to Compare"; })
  2. Dynamically changing the background color of a particular checked checkbox.
      $('input:checked').filter(function() { 
    return $.trim( $(this).val() ) == "Value to Compare"; })

jQuery Dialog in Asp.Net Master Page

May 31, 2013 16 comments

Web developers have been enjoying the elegancy of the jQuery over the years. Many of us have used jQuery Dialog for different purposes.

In this post I’m trying to show how you can easily integrate it in your master page.
You’ll need to import the jquery core and ui libraries before this dialog code.
Define the dialog code in the head section of the master page.
If you want to know all of its properties and configurations then you can find Documentation

<script type="text/javascript">
$(function () {var dialogDefine = $("#divLoginDialog").dialog({
               autoOpen: false,
               modal: true,
               closeOnEscape: true,
               draggable: false,
               resizable: false,
               position: [350, 250],
               title: "Login",
               overlay: "background-color: black; opacity: 90",
               buttons: {
               Cancel: function(){ $(this).dialog('close');},
               Ok: function () { /*Call your custom validation code;*/ }}
         }); //end dialog
$("#hlkShowLogin").click(function () {
});//end Jquery

The hyperlink which will show the dialog is like;

<a href="#" id="hlkShowLogin" class="link">Login</a>

Here’s the login dialog html. In this post I’ve used jQuery buttons, but you can use buttons.
EDIT:: In ASP.Net sample code jQuery buttons replaced with normal buttons.

<div id="divLoginDialog" style="display: none;">
<table cellspacing="0" cellpadding="2">
<td class="label">User Name:</td>
<asp:TextBox ID="txtUserName" ClientIDMode="Static"  runat="server"/>
<asp:RequiredFieldValidator ErrorMessage="User name required" ControlToValidate="txtUserName" runat="server" />
<td class="label">Password:</td>
<asp:TextBox ID="txtPassword" Mode="password" ClientIDMode="Static"  runat="server"/>
<asp:RequiredFieldValidator ErrorMessage="Password required" ControlToValidate="txtPassword" runat="server" />

Here download the sample solution in

MessageBox in ASP.Net using JQuery Impromptu.

March 19, 2013 9 comments

I have been working in for 3 years. But this is my first attempt to write a blog article. It wouldn’t be so good as it should be, but I‘ll to better next time.

In developing web applications it is always very useful to show some nice alerts and popups to get some approvals or feedbacks from user at runtime , e.g. in deleting a record you always use “Are you sure ,you want to delete this order ?” etc. So, Before Trent Richardson’ JQuery-Impromptu, I always used AJAX modalpopup to show windows like MessageBox in But it was slow and also had to do work around much for browser compatibility for AJAX.

Because of these issues I decided to find some other ways to show user some nice looking message-box. When I was Goggling I found JQuery Impromptu by Trent Richardson. It is a very elegant library to use in any web application for popup. You can read more about this library on Trent blog.
Then I found a good article of Aron Goldenthal for using impromptu in I took the idea to write the class from this article. It was little complex that is why I though the need of a class which is easier to use for anyone.

MessageBox is the core class which is responsible to display MessageBox on the browser.

It has the following properties;
Caption: Caption or heading of the MessageBox like Warning, Information, Error, etc.
Message: The text or the description of the MessageBox.
Buttons: Buttons to display on the MessageBox, you can add as many buttons as your requirement. It needs the name of the button and text. It has the following default button types; OK, CANCEL, YES and NO.
Focus: The Index of the button to set the focus at startup, default index is 0.
CallBackFunction: You can have your own custom javascript function to call whenever buttons on the MessageBox is fired. It is optional.

One thing I should mention here is that If you are using AJAX ModalPopup then uncomment the below lines in javascript.

This is the MessageBox;

That is all for this time, I ‘ll come back soon with some enhancements.
Download Sample Application