Monday, October 21, 2019

Client validation


To perform custom client side validation, you have to implement  IClientValidatable interface  and define the GetClientValidationRules method. Inside that method create the new ModelClientValidationRule obj, then initialize the three important property of that object. validationparameters and validationType property names(isvalidage,agevalidation) are used in the client side.


Step 1:  Create the new cs file called isvalidAgeAttribute.cs

Step 2: Copy the below code into the isvalidAgeAttribute.cs file
 
 public class isvalidAgeAttribute : ValidationAttribute,IClientValidatable
    {
        private string _empAge;

        public override bool IsValid(object value)
        {
            if (value != null)
            {
                _empAge = value.ToString();
                _empAge = _empAge.Trim();
                Regex regex = new Regex(@"^[0-9]+$");
                return regex.IsMatch(_empAge);
            }
            return true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context)
        {
            ModelClientValidationRule newRule = new ModelClientValidationRule();
            newRule.ErrorMessage = "Please type your valid age";

            //validationparameters name and validationType name should be small case
            newRule.ValidationParameters.Add("isvalidage", _empAge);
            newRule.ValidationType = "agevalidation";
            yield return newRule;
        }
    }

Now use the custom validation in your model class, just import the namespace and add the
isvalidAge attribute in the age property of employee model as shown.

EmployeeModel.cs

namespace MVC4Examplesbygiri.Models
{
    public class EmployeModel
    {
        public string firstName { get; set; }

        public string lastName { get; set; }

        [isvalidAge(ErrorMessage="Please type your valid age")]
        public string Age { get; set; }

        public decimal Salary { get; set; }
    }
}


In the client side as shown below, you have to create adapter and validator. To create adapter you have to use addSingleVal method as shwon below. The purpose of adapter is to get the meta-data from the render view and pass it to the validator object for validation. The validator object used one method called addMethod for validation as shown below.

View:-

@{
    ViewBag.Title = "customclientValidation";
}

<h2>customclientValidation</h2>

@model MVC4Examplesbygiri.Models.EmployeModel

@*
//for client validation add the following scripts from the scripts folder
*@
@section clientvalidScripts
{
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}


<script type="text/javascript">
    //step 1:- create an adapter
    //first parameter -> reference to ValidationType property name set on the server side
    //second parameter -> reference to ValidationParameters name set on the server side

    $.validator.unobtrusive.adapters.addSingleVal("agevalidation", "isvalidage");

    //step 2:- create a validator
    //first parameter -> reference to validationType property name set on the server side
    //second parameter ->a function to invoke when validation occurrs

    $.validator.addMethod("agevalidation", function (value, element, ageValidation) {

        var age = value;
        if (age.length > 0) {
            var regex = new RegExp('^[0-9]+$', 'g');
            if (age.match(regex))
                return true;
            else
                return false;
        }
        else
            return true;
    });

</script>


@using (Html.BeginForm("customclientValidation", "Home", FormMethod.Post))
{
    <table>
        <tbody>
            <tr>
                <td>
                    @Html.LabelFor(m => m.firstName)
                </td>
                <td>
                    @Html.TextBoxFor(m => m.firstName)

                </td>
            </tr>

            <tr>
                <td>
                    @Html.LabelFor(m => m.lastName)
                </td>
                <td>
                    @Html.TextBoxFor(m => m.lastName)

                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(m => m.Age)
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Age)
                    @Html.ValidationMessageFor(m => m.Age)
                </td>
            </tr>

            <tr>
                <td>
                    @Html.LabelFor(m => m.Salary)
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Salary)
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" id="btn_submit" value="Add Employee" />
                </td>
            </tr>
        </tbody>
    </table>
}

Controller:-

 public ActionResult customclientValidation()
        {
            return View();
        }

        [HttpPost]
        public ActionResult customclientValidation(EmployeModel obj)
        {
            if (ModelState.IsValid)
            {
                //write your code

                //redirect to confirmation page
            }

            //redisplay with errors
            return View();
        }

Different result types - controller action


Hi,
The different types of result types that return by the controller action in order to serve the user request.

Controller:-
  
The controller is responsible for sending the response to the user based on the user request. The Request/Response flow of mvc  is shown below

User Request -> Routing Engine -> Controller -> ViewResult -> ViewEngine -> View

Different Resulttypes return from controller action:-


1.)ViewResult
2)PartialViewResult
3)ContentResult
4)FileContentResult
5)RedirectResult
6)RedirectToRouteResult
7)RedirectResult
8)HttpStatusCodeResult
9)HttpNotFoundResult
10)JsonResult

The above ResultTypes inheriting an abstract class called ActionResult which has an abstract method called ExecuteResult. The ExecuteResult method is override by the above ResultTypes classes. The ExecuteResult responsible for processing the request.

public abstract void ExecuteResult(ControllerContext context);

The controller has convenience methods to return the above resulttypes. Some the methods are

1) View
2)PartialView
3)Json

Example:- The View convenience method creates a System.Web.Mvc.ViewResult object that renders a view to the response.

The user can either use controller convenience method or create an instance of resulttype directly in the controller action. i.e return View()/return new ViewResult()

Example for different result types:-
     
  public ActionResult getView()
        {
            return View();
        }

        public ActionResult getpartialView()
        {
            return PartialView();
        }

        public ActionResult getContent()
        {
            //content() returns content to the user
            return Content("Hello World!", "text",System.Text.Encoding.UTF8);
        }

        public ActionResult getfileContent()
        {
             //string filePath = Path.Combine(@"~/App_Data/", "ErrorLog_" + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt");
             string filePath = Path.Combine(@"~/App_Data/", "sampleData.txt");
              filePath = Server.MapPath(filePath);

            FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read);
            byte[] fileData = new byte[fs.Length];

            fs.Read(fileData,0,System.Convert.ToInt32(fs.Length));

            fs.Close();

            return new FileContentResult(fileData, "text");
        }

        public ActionResult redirecttoAction()
        {
            return RedirectToAction("About", "Home");
        }

        public ActionResult redirecttorouteDemo()
        {
            return RedirectToRoute("testRoute", new { Controller="Home",Action="About", productId = 44 });
        }

        public ActionResult redirectDemo()
        {
            return Redirect("http://giri-aspdotnet.com");
        }

        public ActionResult httpstatusCodeResult()
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound, "The request resource does not exist in the server.");
        }

        public ActionResult httpnotFoundResult()
        {
           return new HttpNotFoundResult("File Not Found in mvc4examplesbygiri");
        }

        public ActionResult getjsonData()
        {
            //use ajax call to get the reponse as json data
            return  Json(new { data = "Sample Json Data" });
        }


Create select element


View:-
@{
    ViewBag.Title = "dynamicDropdown";
}

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<h2>Dynamic Dropdown using Jquery</h2>

<div id="div_cntr">
</div>


<script type="text/javascript">
    $(function () {

        //get the list of items
        var deliverydrpDown = @Html.Raw(Json.Encode(@ViewBag.Fruits));

        var dd1 = document.createElement("select");
        dd1.name = "dynmcdrp_fruits";
        dd1.id = "dynmcdrp_fruits";
           
        $.each(deliverydrpDown,function(index,item)
        {
            //alert(item.Text);
            dd1.options[dd1.length] = new Option(item.Text, item.Text);
        });

       //for dropdown onchange event
        dd1.onchange = function() {
            var drp = document.getElementById('dynmcdrp_fruits');
            var selValue = drp.options[drp.selectedIndex].value;
            customDialog("Information","Selected fruit is:- "+selValue);
        };
        
        //to set the selected item
        //for (var i = 0; i < dd1.options.length; i++) {
        //    if (dd1.options[i].text == text) {
        //        dd1.selectedIndex = i;
        //        break;
        //    }
        //}

        $('#div_cntr').append(dd1);

    });

    //jquery custom dialog box to display  exception
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }

</script>


Controller:-
    public ActionResult dynamicDropdown()
        {

            List<SelectListItem> fruits = new List<SelectListItem>();
            fruits.Add(new SelectListItem { Text = "Apple", Value = "Apple" });
            fruits.Add(new SelectListItem { Text = "Orange", Value = "Orange" });
            fruits.Add(new SelectListItem { Text = "Mango", Value = "Mango" });
            ViewBag.Fruits = fruits;

            return View();
        }

Selected value in dropdown


View:-

@{
    ViewBag.Title = "selectElement";
}

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<h2>select Element</h2>


<label for="drp_fruits">Select fruit:- </label>
<select id="drp_fruits">
  <option value="Apple">Apple</option>
  <option value="Orange">Orange</option>
  <option value="Mango">Mango</option>
  <option value="Cucumber">Cucumber</option>
</select>

<br />
<br />
<input type="button" id="btn_selfruit" value="Get selected fruit" /> &nbsp;&nbsp;
<input type="button" id="btn_setselfruit" value="Select typed fruit" /> &nbsp;&nbsp;
<input type="text" id="txt_typedfruit" />


<script type="text/javascript">

    $(function () {
        $('#btn_selfruit').click(function () {
            var val = $('#drp_fruits option:selected').text();
            $(this).css('color', 'blue');
            $(this).css('text-decoration', 'underline');
            $(this).css('font-weight', 'bold');
            customDialog("Information", "Selected fruit is:- " + val);


        });


        $('#btn_setselfruit').click(function () {
            $(this).css('color', 'blue');
            $(this).css('text-decoration', 'underline');
            $(this).css('font-weight', 'bold');
            $('#drp_fruits option[value="' + $('#txt_typedfruit').val()  + '"]').attr("selected", true);
        });
    });

    //jquery custom dialog box to display  exception
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }

</script>


Controller:-

 public ActionResult selectElement()
        {
            return View();
        }

Selected value in radio button



@{
    ViewBag.Title = "RadioButton";
}

<h2> RadioButton</h2>

 <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />


<input type="button" id="btn_selectedVal" value="Get Selected Fruit" />

 <input type="radio" value="Apple"  name="rdo_fruits" checked="checked" />Apple &nbsp;&nbsp;
 <input type="radio" value="Orange" name="rdo_fruits"  />Orange

<script type="text/javascript">
    $('#btn_selectedVal').click(function () {

        var val = $("input[name='rdo_fruits']:checked").val();

        customDialog("Information", "Selected fruit is:- " + val);
    });

    //jquery custom dialog box to display  exception
    function customDialog(headerValue, message) {
        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');
        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }
</script>


Controller:-

   public ActionResult RadioButton()
        {
            return View();
        }


Tuesday, October 15, 2019

Delete a jquery tab


@{
    ViewBag.Title = "deletetabsDynamically";
}

<h2>deletetabsDynamically</h2>

  <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<input type="button" id="btn_deletetab" onclick="deleteTab();" value="Delete Tab" />

<div id="div_tab">
    <ul>
        <li>
            <a href="#div_tab1">Tab1</a>
        </li>
        <li>
            <a href="#div_tab2">Tab2</a>
        </li>
        <li>
            <a href="#div_tab3">Tab3</a>
        </li>
    </ul>

    <div id="div_tab1">
        <h1>Inside tab1</h1>
    </div>
    <div id="div_tab2">
        <h1>Inside tab2</h1>
    </div>
    <div id="div_tab3">
        <h1>Inside tab3</h1>
    </div>
</div>

<script type="text/javascript">

    var deleteIndex;

    $(function () {

        $('#div_tab').tabs();

        $("#div_tab").bind('tabsselect', function (event, ui) {
            deleteIndex = ui.index;
        });  
    });

    //to delete the clicked tab
    function deleteTab() {
        customConfirm('Do you want to delete this tab ?',
           function () {
               $('#div_tab').tabs('remove', deleteIndex);
           },
        function () {
        },
        'Confirm Delete'
);
    }

    function customConfirm(dialogText, okFunc, cancelFunc, dialogTitle) {
        $('<div style="padding: 10px; max-width: 500px; word-wrap: break-word;">' + dialogText + '</div>').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: dialogTitle || 'Confirm',
            minHeight: 75,
            buttons: {
                OK: function () {
                    if (typeof (okFunc) == 'function') { setTimeout(okFunc, 50); }
                    $(this).dialog('destroy');
                },
                Cancel: function () {
                    if (typeof (cancelFunc) == 'function') { setTimeout(cancelFunc, 50); }
                    $(this).dialog('destroy');
                }
            }
        });
    }

</script>

Controller:-

    public ActionResult deletetabsDynamically()
        {
            return View();
        }

Create a jquery tab




@{
    ViewBag.Title = "addtabsDynamically";
}

  <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<h2>addtabsDynamically</h2>

<input type="text" id="txt_newtab" />&nbsp;&nbsp;
<input type="button" id="btn_addtab" value="Add New Tab" />
<br />
<br />

<div id="div_tab">
    <ul id="ul_addtabsdynmicly">
        <li>
            <a href="#div_tab1">Tab1</a>
        </li>
        <li>
            <a href="#div_tab2">Tab2</a>
        </li>
        <li>
            <a href="#div_tab3">Tab3</a>
        </li>
    </ul>

    <div id="div_tab1">
        <h1>Inside tab1</h1>
    </div>
    <div id="div_tab2">
        <h1>Inside tab2</h1>
    </div>
    <div id="div_tab3">
        <h1>Inside tab3</h1>
    </div>
</div>


<script type="text/javascript">

    $(function () {
        $('#div_tab').tabs();

        $('#btn_addtab').click(function () {

            var tabCntr = $('#div_tab');
            var header = $('#txt_newtab').val();
            var id = parseInt($('#ul_addtabsdynmicly li').length);
            id++;
            var dydivid = "dytab_" + id;
            $("<div id='" + dydivid + "'><p>Inside the'" + header + "'</p></div>").appendTo(tabCntr);

            //to set the newly added tab as selected tab
            var seltab = parseInt($('#ul_addtabsdynmicly li').length);

            //to add new tabs
            $(tabCntr).tabs({
                fx: { opacity: "toggle" },
                add: function (event, tab) {
                    //$(tab.panel).load("dytab_" + $(this).text());
                }
               
            }).tabs("add", "#dytab_" + id, header);

            sletab = seltab - 1;

            $(tabCntr).tabs({
                selected: seltab
            });

        });

    });
</script>

Controller:-


   public ActionResult addtabsDynamically()
        {
            return View();
        }

Load content in the jquery tab




@{
    ViewBag.Title = "loadingtabsDynamically";
}


    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<h2>loadingtabsDynamically</h2>

<div id="div_tab">
    <ul>
        <li>
            <a href="#div_tab1">Tab1</a>
        </li>
        <li>
            <a href="#div_tab2">Tab2</a>
        </li>
        <li>
            <a href="#div_tab3">Tab3</a>
        </li>
    </ul>

    <div id="div_tab1">
        <h1>Inside tab1</h1>
    </div>
    <div id="div_tab2">
        <h1>Inside tab2</h1>
    </div>
    <div id="div_tab3">
        <h1>Inside tab3</h1>
    </div>
</div>


<script type="text/javascript">
    $(function () {

        $('#div_tab').tabs();

    });

    //In the tab select event, get the selected tab
    $("#div_tab").on("tabsselect", function (event, ui) {
        var tabnumber = ui.index;
        var tabName = $(ui.tab).text();

        if (tabName == "Tab1") {
            //make ajax call here to load data dynamically for tab1
            $('#div_tab1').html('<b>tab1 data loaded dynamically</b>');
        }
        else if (tabName == "Tab2") {
            //make ajax call here to load data dynamically for tab2
            $('#div_tab2').html('<b>tab2 data loaded dynamically</b>');
        }
        else if (tabName == "Tab3") {
            //make ajax call here to load data dynamically for tab3
            $('#div_tab3').html('<b>tab3 data loaded dynamically</b>');
        }

    });
</script>

Controller:-


  public ActionResult loadingtabsDynamically()
        {
            return View();
        }

Custom alert dialog




@{
    ViewBag.Title = "customAlert";
}

<h2>customAlert</h2>

<input type="button" id="btn_customalert" value="Open Custom Alert" />


<script type="text/javascript">

    $(function () {

        $('#btn_customalert').click(function () {

            customDialog('Information', 'Custom alert demo');
        });
    });

    //for jquery custom dialog box
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }
</script>


Update html table column header text




@{
    ViewBag.Title = "modifycolumnHeader";
}

<h2>Modify Column Header</h2>

<table  id="tbl_customers">
    <thead>
        <tr>
<th>Customer ID</th><th>Name</th><th>Age</th><th>Account Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<td>1</td><td>Ram</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>2 </td><td>Balu</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>3</td><td>Sidhu</td><td>25</td><td>Savings Account</td>
        </tr>
    </tbody>
 </table>


<script type="text/javascript">
    $(function () {

        var tbl = $('#tbl_customers');

        //change the cursor to hand on hovering the columns
        $(tbl).find('thead tr th').hover(function () {
            $(this).css('cursor', 'pointer');
        });


        //open jquery dialog to modify column header on double click of column header
        $(tbl).find('thead tr th').unbind('dblclick').dblclick(function () {
            var currentHeader = $(this);
            var oldheaderText = $(this).html();
            custominputDialog(currentHeader, oldheaderText);

        });

    });

    //for jquery custom dialog box
    function custominputDialog(currentHeader, oldheaderText) {

        //remove the existing div
        var divs = $('body').find('div[id="div_custominputDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_custominputDialog"><input type="text" id="txt_colheader"/></div>');

        var txtinput = $('#div_custominputDialog').find('#txt_colheader');
        $(txtinput).val(oldheaderText);
      
        $('#div_custominputDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: 'Modify header',
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(currentHeader).html($('#div_custominputDialog').find('#txt_colheader').val());

                    $(this).dialog('close');
                    $(this).dialog('destroy');
                },
                CANCEL: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_custominputDialog').dialog('open');
    }
</script>


Controller:-

  public ActionResult modifycolumnHeader()
        {
            try
            {
                return View();
            }
            catch (Exception)
            { }
            return null;
        }


Add/Remove a column in html table



@{
    ViewBag.Title = "addremoveColumns";
}

<h2>Add/Remove Columns</h2>

<input type="button" id="btn_addcolumn" value="Add Column" /> <br />
<input type="button" id="btn_deletecolumn" value="Delete Column" />

<table  id="tbl_customers">
    <thead>
        <tr>
<th>Customer ID</th><th>Name</th><th>Age</th><th>Account Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<td>1</td><td>Ram</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>2 </td><td>Balu</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>3</td><td>Sidhu</td><td>25</td><td>Savings Account</td>
        </tr>
    </tbody>
 </table>





<script type="text/javascript">
    $(function () {

        var tbl = $('#tbl_customers');

        //change the cursor to hand on hovering the columns
        $(tbl).find('thead tr th').hover(function () {
            $(this).css('cursor', 'pointer');
        });

        //for setting the cssclass for the selected column header and cells, for deletion
        $(tbl).find('thead tr th').click(function () {

            $('#tbl_customers thead tr th').css('background-color', '');
            $('#tbl_customers tbody tr td').css('background-color', '');
            $('#tbl_customers thead tr th').removeClass('selectedHeader');
            $('#tbl_customers tbody tr td').removeClass('selectedCell');

            $(this).addClass('selectedHeader');
            $(this).css('background-color', 'lightblue');
            var index = $(this).index() + 1;
            var tbl = $('#tbl_customers');
            var tds = $(tbl).find('td:nth-child(' + index + ')');
            $(tds).addClass('selectedCell');
            $(tds).css('background-color', 'lightblue');
        });
    });

    //add column button click event
    $('#btn_addcolumn').unbind("click").click(function () {

        //for adding column header
        var tbl = $('#tbl_customers');
        var gridhdrRow = $(tbl).find('thead tr').first();
        var gridhdrCell = $(gridhdrRow).find('th');

        $(gridhdrRow).append('<th style="width:80px;"></th>');
    


        //adding cells for newly added header column
        var noofRows = $(tbl).find('tbody tr');
        var cellLength;
        $.each(noofRows, function (index, row) {
            $(row).append('<td style="width:80px;" class="RowCell"></td>');
        });
      
        //change the cursor to hand on hovering the columns
        $(tbl).find('thead tr th').hover(function () {
            $(this).css('cursor', 'pointer');
        });
      
        //for setting the cssclass for the selected column header and cells, for deletion
        $(tbl).find('thead tr th').click(function () {

            $('#tbl_customers thead tr th').css('background-color', '');
            $('#tbl_customers tbody tr td').css('background-color', '');
            $('#tbl_customers thead tr th').removeClass('selectedHeader');
            $('#tbl_customers tbody tr td').removeClass('selectedCell');
          
            $(this).addClass('selectedHeader');
            $(this).css('background-color', 'lightblue');
            var index = $(this).index() + 1;
            var tbl = $('#tbl_customers');
            var tds = $(tbl).find('td:nth-child(' + index + ')');
            $(tds).addClass('selectedCell');
            $(tds).css('background-color', 'lightblue');
        });
    
    });


    //for remove column button click event
    $('#btn_deletecolumn').unbind("click").click(function () {

        //for removing the selected column header
        var tbl = $('#tbl_customers');
        var gridhdrRow = $(tbl).find('thead tr').first();
        var gridhdrCell = $(gridhdrRow).find('th.selectedHeader');

        var delCnt = $(gridhdrCell).html();
      
        if (delCnt == null) {
            customDialog("Warning", "Please select column to delete");
        }
        else { //for removing selected header
            $(gridhdrCell).remove();
            customDialog("Delete Confirmation", "Column deleted successfully.");
        }

    
        //for removing selected cells from the content table
        var noofRows = $(tbl).find('tbody tr');
        $.each(noofRows, function () {
            var selectedTd = $(this).find('td.selectedCell');
            $(selectedTd).remove();
        });
      

    });

    //for jquery custom dialog box
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }

</script>


Controller:-

  public ActionResult addremoveColumns()
        {
            try
            {
                return View();
            }
            catch (Exception)
            { }
            return null;
        }

Add/Remove a row in html table - Jquery



@{
    ViewBag.Title = "addremoveRows";
}

<h2>Add/Remove Rows</h2>

<input type="button" id="btn_addrow" value="Add Row" /> <br />
<input type="button" id="btn_deleterow" value="Delete Row" />

<table  id="tbl_customers">
    <thead>
        <tr>
<th>Customer ID</th><th>Name</th><th>Age</th><th>Account Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<td>1</td><td>Ram</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>2 </td><td>Balu</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>3</td><td>Sidhu</td><td>25</td><td>Savings Account</td>
        </tr>
    </tbody>
 </table>


<script type="text/javascript">
    $(function () {

        var tbl = $('#tbl_customers');

        //on hover change the mouse pointer to hand
        $(tbl).find('tbody tr').hover(function () {
            $(this).css('cursor', 'pointer');
        });

        //on the click of the row add foreground color for deletion
        $(tbl).find('tbody tr').click(function () {
            $(tbl).find('tbody tr').removeClass('selectedRow');  //empty class, to identify row for deletion
            $(tbl).find('tbody tr').css('color', '');
            $(this).addClass('selectedRow');
            $(this).css('color', 'blue');
        });
      
    });



    //for delete row button click event
    $('#btn_deleterow').unbind("click").click(function () {

        //for removing the row from the grid
        var tbl = $('#tbl_customers');
        var noofRows = $(tbl).find('tbody tr').length;

        //for empty table without rows
        if (noofRows == 0) {
            return;
        }
        var tBody = $(tbl).find('tbody');
        var deleteRow = $(tBody).find('tr.selectedRow');
      
        var delCnt = $(deleteRow).html();
        if (delCnt == null) {
            customDialog("Warning", "Please select row to delete");
        }
        else {
            customDialog("Delete Confirmation", "Row Deleted Successfully");
            $(deleteRow).remove();
        }
    });

    //for add row button click event
    $('#btn_addrow').unbind('click').click(function () {

        //for adding dynamic rows

        //for getting no of cells
        var tbl = $('#tbl_customers');
        var gridhdrRow = $(tbl).find('thead tr').first();
        var gridhdrCell = $(gridhdrRow).find('th');
        var noofCells = 0;
        noofCells = $(gridhdrCell).index();
        //end of getting no of cells

        //for getting no of rows
        var rowLength = 0;
        rowLength = $(tbl).find('tbody tr').length;
        rowLength++;
        //end of getting no of rows

        //for empty table without header
        var tbl = $('#tbl_customers');
        var gridhdrRow = $(tbl).find('thead tr').first();
        var gridhdrCell = $(gridhdrRow).find('th');
        if ($(gridhdrCell).length == 0) {
            return;
        }
        //end of empty table without header


        //create rows dynamically
        //for empty table
        var dynmicRow = $('<tr></tr>');
        while (noofCells >= 0) {

            $(dynmicRow).append('<td style="width:80px;height:15px;"></td>');
            noofCells--;
        }
        var tbody = $(tbl).find('tbody');
        $(tbody).append(dynmicRow);
        //end of creating dynamic rows

        //on hover change the mouse pointer to hand
        $(tbl).find('tbody tr').hover(function () {
            $(this).css('cursor', 'pointer');
        });
     
        //on the click of the row add css for deletion
        $(tbl).find('tbody tr').click(function () {
       
            $(tbl).find('tbody tr').removeClass('selectedRow');
            $(tbl).find('tbody tr').css('color', '');


            $(this).addClass('selectedRow');
            $(this).css('color', 'blue');
        });
      
    });


    //for jquery custom dialog box
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }
   


</script>


Controller:-

 public ActionResult addremoveRows()
        {
            try
            {
                return View();
            }
            catch (Exception)
            { }
            return null;
        }



Select html table column by double click the column header - Jquery




@{
    ViewBag.Title = "selcolondblClick";
}

<h2>Select Column</h2>

<table  id="tbl_customers">
    <thead>
        <tr>
<th>Customer ID</th><th>Name</th><th>Age</th><th>Account Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<td>1</td><td>Ram</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>2 </td><td>Balu</td><td>20</td><td>Student Account</td>
        </tr>
        <tr>
<td>3</td><td>Sidhu</td><td>25</td><td>Savings Account</td>
        </tr>
    </tbody>
 </table>


<script type="text/javascript">
    $(function () {

        var tbl = $('#tbl_customers');

        //on hover change the mouse pointer to hand
        $(tbl).find('thead tr th').hover(function () {
            $(this).css('cursor', 'pointer');
        });

        //for adding cssclass to selected header cell
        $(tbl).find('thead tr th').dblclick(function () {
            $('.selectedHeader').removeClass();
            $('.selectedCell').removeClass();


            $(this).addClass('selectedHeader');
            var index = $(this).index() + 1;
            var tbl = $('#tbl_customers');
            var tds = $(tbl).find('td:nth-child(' + index + ')');
            $(tds).addClass('selectedCell');
        });
        //end of adding cssclass to selected  header cell

    });
</script>


<style type="text/css">
    .selectedHeader {
        background-color:gray;
    }

    .selectedCell {
        background-color: gray;
    }
</style>


Controller:-

   public ActionResult selcolondblClick()
        {
            try
            {
                return View();
            }
            catch (Exception)
            { }
            return null;
        }