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;
        }

Inline cell editing in html table - Jquery




@{
    ViewBag.Title = "inlinecellEditing";
}

<h2>Inline Cell Editing</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');
        //inline cell editing for the initially loaded rows
        $(tbl).find('tbody tr td').dblclick(function () {
            var text = $(this).text();
            $(this).text("");
            var textBox = document.createElement('input');
            textBox.setAttribute('type', 'text');
            textBox.setAttribute('onkeypress', 'onKeyPress(event,this)');
            $(textBox).val(text);
            $(this).append(textBox);
        });
        //end of inline cell editing for the initially loaded rows
    });

    //for inline cell editing
    function onKeyPress(event, txtbx) {
        if (event.keyCode == 13) {
            var parentTd = $(txtbx).closest('td');
            var typedVal = $(txtbx).val();
            $(txtbx).remove();
            $(parentTd).text(typedVal);

        }
    }
</script>


Controller:-

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

Monday, October 14, 2019

Add rows in the html table - Jquery


Hi,
It adds rows in the html table by jquery.

<script type="text/javascript">

    $(function()
    {
   
        var array = @Html.Raw(Json.Encode(@ViewBag.columnHeaders));

        //while loading the view change the gridview header based on the column header list
        var tbl =  $('#tbl_customers');
        var gridhdrRow = $(tbl).find('thead tr').first();
        for(var i=0;i<array.length;i++)
        {
            var hdrcell ='<th style="width:80px;">'+array[i]+'</th>';
            $(gridhdrRow).append(hdrcell);
        }
        //end

        //while loading the view load the rows
        var rowArray = @Html.Raw(Json.Encode(@ViewBag.rows));
     
        data = $.parseJSON(JSON.stringify(rowArray));

        //to iterate the rows
        $.each(data, function(i, item) {
         
            //getting the rowlength
            var rowLength = 0;
            rowLength = $(tbl).find('tbody tr').length;
            rowLength++;
            //end of getting the rowlength

            var dynmicRow = $('<tr><td style="width:80px;">' + rowLength + '</td>');

            //to iterate each column in the row
            $.each(item,function(index)
            {
                var colValue = item[index];
                var strcolValue = colValue.toString();
                $(dynmicRow).append('<td style="width:80px;">'+strcolValue +'</td>');
            });

            //adding new row to the table
            var tbody = $(tbl).find('tbody');
            $(tbody).append(dynmicRow);

        });
        //end of loading the rows

   
    });

</script>


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

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

 <table  id="tbl_customers">
                          <thead>
                              <tr>
                              </tr>
                          </thead>
                          <tbody>
                          </tbody>
                      </table>


Controller:-

 public ActionResult Index()
        {
            ViewBag.Message = "Dynamically creating rows in html table using Jquery";
            List<CustomerModel> rowsList = new List<CustomerModel>();
            rowsList.Add(new CustomerModel { customerName = "Balu", Age = "20", accountType = "Student"});
            rowsList.Add(new CustomerModel { customerName = "Sidhu", Age = "22", accountType = "Student"});
            rowsList.Add(new CustomerModel { customerName = "Sharma", Age = "30", accountType = "Savings" });

            List<string> columHeadersList = new List<string>();
            columHeadersList.Add("ID");
            columHeadersList.Add("customerName");
            columHeadersList.Add("Age");
            columHeadersList.Add("accountType");
          


            ViewBag.columnHeaders = columHeadersList;
            ViewBag.rows = rowsList;

            return View();
        }

Model:-

 public class CustomerModel
    {
        public string customerName { get; set; }
        public string accountType { get; set; }
        public string Age { get; set; }
    }

Select the option in html drop down - Jquery


Hi,
Preselect the option in multiple dropdowns by jquery, on the click of link buttons.


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.js"></script>
  
  <script type="text/javascript">

        function selectdropDown(txt) {

          
            var drp1 = document.getElementById('<%=drp_colors1.ClientID%>');
            var drp2 = document.getElementById('<%=drp_colors2.ClientID%>');
            var drp3 = document.getElementById('<%=drp_colors3.ClientID%>');

            if (drp1.options[drp1.selectedIndex].value == "--Select Colors--") {
               $(drp1).find("option[value='"+txt+"']").prop('selected', true);
            }
            else if (drp2.options[drp2.selectedIndex].value == "--Select Colors--") {
                $(drp2).find("option[value='" + txt + "']").prop('selected', true);
            }
            else if (drp3.options[drp3.selectedIndex].value == "--Select Colors--") {
                $(drp3).find("option[value='" + txt + "']").prop('selected', true);
            }
               
            }
    </script>
</head>
<body  style="background-color:lightgray;">
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="drp_colors1" runat="server">
            <asp:ListItem>--Select Colors--</asp:ListItem>
            <asp:ListItem>Red</asp:ListItem>
            <asp:ListItem>Green</asp:ListItem>
            <asp:ListItem>Blue</asp:ListItem>
        </asp:DropDownList><br />
        <asp:DropDownList ID="drp_colors2" runat="server">
             <asp:ListItem>--Select Colors--</asp:ListItem>
            <asp:ListItem>Red</asp:ListItem>
            <asp:ListItem>Green</asp:ListItem>
            <asp:ListItem>Blue</asp:ListItem>
        </asp:DropDownList><br />
        <asp:DropDownList ID="drp_colors3" runat="server">
             <asp:ListItem>--Select Colors--</asp:ListItem>
            <asp:ListItem>Red</asp:ListItem>
            <asp:ListItem>Green</asp:ListItem>
            <asp:ListItem>Blue</asp:ListItem>
        </asp:DropDownList><br />
        <br />
        <asp:LinkButton runat="server" OnClientClick="selectdropDown('Red');" ID="lnk_colors1" Text="Red" />
        <br />
        <asp:LinkButton runat="server" OnClientClick="selectdropDown('Green');" ID="lnk_colors2" Text="Green" />
        <br />
        <asp:LinkButton runat="server" OnClientClick="selectdropDown('Blue');" ID="lnk_colors3" Text="Blue" />
    </div>
    </form>
</body>
</html>

Jquery confirmation dialog

Hi,
The code gets asp.net textbox value by jquery then display it in the jquery confirmation dialog.
.aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="../Scripts/jquery-ui.js"></script>
    <link href="../Scripts/jquery-ui.css" rel="stylesheet" />
 
   <script type="text/javascript">
        function verifyUserName() {
         
            customDialog('you have registered ' +
          $('#<%=TextBox1.ClientID %>').val());
      }

        function customDialog(msg) {

            //for yes or no dialog
            $('#div_sexpired').remove();
            var dialog = $('<div id="div_sexpired"></div>').text(msg);
            $('body').append(dialog);

            $('#div_sexpired').dialog({
                autoOpen: false,
                modal: true,
                title: 'Verify User Name',
                buttons: {
                    "OK": function () {

                        $(dialog).dialog('close');
                        $('#div_sexpired').remove();
                    }
                }

            });

            $('#div_sexpired').dialog('open');

        }
     
        </script>


</head>
<body style="background-color:lightblue;">
    <form id="form1" runat="server">
      
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <input type="button" id="btn_verifyusername" onclick="verifyUserName();" value="Verify User" />
    </div>
    </form>
</body>
</html>



Add a new column in the gridview on client side by jquery

Hi,
In this article i populate the gridview with the students marks. While rendering the gridview, i get the mark1 and mark2  of the student, then i calculate total marks of the student. I am adding the student total marks in the student row as a new column with name "Total Marks" using jquery.
.aspx page

<head runat="server">
    <title></title>
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(function () {

            $('table#grdvw_students tr').each(function () {
                var txt1 = $(this).find('td:nth-child(3)').find('span').text(); //get the mark1
                var txt2 = $(this).find('td:nth-child(4)').find('span').text(); //get the mark2

                if (txt1 != "" & txt2 != "") {
                    var mark1 = parseInt(txt1);
                    var mark2 = parseInt(txt2);
                    var sum = mark1 + mark2; //sum of mark1 and mark2

                    //creating new column for total marks in each row
                    $(this).append("<td><span style='color:blue;'>" + sum + "</span></td>");

                }
                else { //for header text
                    $(this).append("<td><span  style='color:blue;'>Total Marks</span></td>");
                }

               
            });
        });
    </script>
</head>

  <body>
    <form id="form1" runat="server">
    <div>
      <asp:GridView ID="grdvw_students" AutoGenerateColumns="false"  runat="server">
          <Columns>
             <asp:TemplateField HeaderText="Student Id">
                 <ItemTemplate>
                     <asp:Label  ID="lbl_studid" runat="server" Text='<%# Eval("StudentId") %>' />
                 </ItemTemplate>
             </asp:TemplateField>
              <asp:TemplateField HeaderText="Student Name">
                  <ItemTemplate>
                      <asp:Label ID="lbl_name" runat="server" Text='<%# Eval("Name") %>' />
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="Mark1">
                  <ItemTemplate>
                      <asp:Label ID="lbl_mark1" runat="server" Text='<%# Eval("Mark1") %>' />
                  </ItemTemplate>
              </asp:TemplateField>
               <asp:TemplateField HeaderText="Mark1">
                  <ItemTemplate>
                      <asp:Label ID="lbl_mark2" runat="server" Text='<%# Eval("Mark2") %>' />
                  </ItemTemplate>
              </asp:TemplateField>
          </Columns>
        </asp:GridView>
    </div>
    </form>
</body>

Code behind:-

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindgridView();
            }

        }

        private void bindgridView()
        {
            try
            {

                SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwindconstring"].ToString());

                List<Students> lst = new List<Students>();
                lst.Add(new Students { studId = 1, Name = "Giri", Mark1 = 90,Mark2=90 });
                lst.Add(new Students { studId = 2, Name = "Watson", Mark1 = 40,Mark2=50 });
                lst.Add(new Students { studId = 3, Name = "Bala", Mark1 = 80,Mark2=60 });
                lst.Add(new Students { studId = 4, Name = "Jim", Mark1 = 45,Mark2=45 });

                DataTable dt = new DataTable();
                DataRow dr;
                dt.Columns.Add("StudentId", typeof(string));
                dt.Columns.Add("Mark1", typeof(string));
                dt.Columns.Add("Mark2", typeof(string));

                foreach (var item in lst)
                {
                    dr = dt.NewRow();
                    dr["StudentId"] = item.studId;
                    dr["Mark1"] = item.Mark1;
                    dr["Mark2"] = item.Mark2;
                    dt.Rows.Add(dr);
                }

                //add the new column in to the existing datatable 
                DataColumn newColumn = new DataColumn("Name",typeof(string));
                newColumn.DefaultValue = "Your Project Name";
                dt.Columns.Add(newColumn);

                
                grdvw_students.DataSource = dt;
                grdvw_students.DataBind();

            }
            catch (Exception)
            { }
        }
    }

    public class Students
    {
        public int studId { get; set; }
        public string Name { get; set; }
        public int Mark1 { get; set; }
        public int Mark2 { get; set; }

    }