DataTable : Add checkbox in jquery datatable and handle button event


DataTable : Add checkbox in jquery datatable and handle button event


How to add checkbox in jquery datatable and how to manage selected list on button click event. Solution is below,

HTML

 <fieldset class="clearfix fs-border">
            <legend class="fs-border">User's List:</legend>
            <div class="box-body">
                <table id="myTable" class="display responsive table table-striped dataTable no-footer" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th class="text-center"><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>Mobile</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                </table>
                <input type="button" id="btnSubmit" value="Submit Data" class="btn btn-default" />
            </div>
        </fieldset>

JQuery:

 var table = "";
var count = 0;
var totalCount = 0;
var checkedCount = 0;
 
$(document).ready(function () {
    $("#messagebox").hide();
    table = $("#myTable").DataTable({
        "processing"true,
        "serverSide"true,
        "filter"true,
        "orderMulti"false,
        "paging"true,
        "responsive"true,
        "ajax": {
            "type""POST",
            "url""ControllerName/GetJsonData",
            "dataSrc"function (data) {
                //Make your callback here.                
                if (data.value == "fail") {
                    window.location = "Unauthorised";
                } else {
                    //console.log(data);
                }
                countall(data.data);
                return data.data;
            }
        },
        "columnDefs": [{
            "targets": 0,
            "searchable"false,
            "orderable"false,
            "className""dt-body-center",
            "render"function (data, type, full, meta){
                return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
            }
        }],
        "order": [[1, "asc"]],
        "columns": [
            {
                data: null,
                orderable: false,
                width: 100,
                render: function (data, type, row) {
                    //console.log(data);
                    return "<input type='checkbox' id='" + data.userId + "'> "
                }
            },
               { "data""FirstName""name""FirstName" },
               { "data""LastName""name""LastName" },
               { "data""Email""name""Email" },
               { "data""Mobile""name""Mobile" },
               { "data""Status""name""Status" },
        ]
       
    });
 
    function countall(data)
    {
        totalCount =  data.length;        
    }
 
    // Handle click on "Select all" control
    $('#example-select-all').on('click'function () {
        // Get all rows with search applied
        var rows = table.rows({ 'search''applied' }).nodes();
        // Check/uncheck checkboxes for all rows in the table
        $('input[type="checkbox"]', rows).prop('checked'this.checked);
    });
 
    // Handle click on checkbox to set state of "Select all" control
    $('#myTable tbody').on('change''input[type="checkbox"]'function () {
        // If checkbox is not checked
        if (!this.checked) {
            var el = $('#example-select-all').get(0);
            // If "Select all" control is checked and has 'indeterminate' property
            if (el && el.checked && ('indeterminate' in el)) {
                // Set visual state of "Select all" controlas 'indeterminate'
                el.indeterminate = true;
            }
        }

      /// Set select all checkbox tick and untick
       checkedCount=0;
       table.$('input[type="checkbox"]').each(function () {
           if (this.checked) {                
               checkedCount++;               
               if(totalCount==checkedCount)
               {                    
                   $('#push-select-all').prop("indeterminate"false);
                   $('#push-select-all').prop('checked'true);
               }
           }            
       });

    });
 
 
    // Handle send event for selected users
    $('#btnSubmit').on('click'function (e) {
         
        var membersList = [];
            
        // Iterate over all checkboxes in the table
        table.$('input[type="checkbox"]').each(function () {        
            if (this.checked) {
                membersList.push({ userId: $(this).attr('id') });
                //console.log($(this).attr('id'));
                count++;
            }
        });
 
        if (count == 0)
        {
            alert("Please select atleast one user to submit data.");
        } 
        else {
            $.ajax({
                type: "POST",
                url: "ControllerName/ActionMethodName",
                contentType: 'application/json',             
                data: "{userList :" + JSON.stringify(membersList) + ",message :\"" + $("#Message").val() + "\"}",
                success: function (retdata) {                    
                    if (retdata == "success")
                        alert("Message sent successfully.");
                    else
                        alert(retdata);
                    
                }
            });
        }
       
    }); 
});

 

C# Code:

 [HttpPost]
        public JsonResult ActionMethodName(List<VMUsers> userList, string message)
        {
            var returnMessage = "business return message";
 
            return Json(returnMessage, JsonRequestBehavior.AllowGet);
        }
 
public class VMUsers
   {
       public string userId { getset; }
   } 


Enjoy !!!

 :)

ASP.Net, MVC - Get Client MAC ID


ASP.Net, MVC  - Get Client MAC ID



Below code gives client's mac id...

using System.Runtime.InteropServices;
 
namespace Demo.Common
{
    public class GetMACid
    {
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
 
        public static string getID()
        {
            string mac_dest = "";
            try
            {
                string userip = HttpContext.Current.Request.UserHostAddress;
                string strClientIP = HttpContext.Current.Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP);
                Int32 lhost = inet_addr("");
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }
 
               
 
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
            }
            catch (Exception err)
            {
                return err.Message;
            }
            return mac_dest;
        }
    }
}


Enjoy !!!

:)

Linq Queries - Update data in query

Linq Queries - Update data in query



how to update an item in a list by linq

public static class UpdateExtensions
    {
        public delegate void Func<TArg0>(TArg0 element);

        public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> update)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (update == null) throw new ArgumentNullException("update");
            if (typeof(TSource).IsValueType)
                throw new NotSupportedException("value type elements are not supported by update.");

            int count = 0;
            foreach (TSource element in source)
            {
                update(element);
                count++;
            }
            return count;
        }
    }


Use update extension

var Datas = from ev in db.Events
                            join ea in db.EventAttendees on ev.EventId equals ea.EventId
                            where ea.UserId == userid
                            select new VMEvent
                            {
                                EventName = ev.EventName,
                                EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                                Place = ev.Place, 
                                EventAttendeeNoofMembers = ea.noofMembers.ToString() 
                             }; 
  var query = (from items in Datas
                             select items)
                          .Update(st => { st.EventDateString = st.EventDate.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);  });


Enjoy !!!
:)


Linq Queries


Linq Queries



Join and custom selected columns with some expression,

 var Datas = from ev in db.Events
                            join ea in db.EventAttendees on ev.EventId equals ea.EventId
                            join u in db.Users on ea.UserId equals u.UserId
                           // where ea.UserId == userid
                            select new VMEvent
                            {
                                EventName = ev.EventName,
                                EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                                Place = ev.Place,
                                EventDateString = ev.EventDate.ToString(),
                                EventAttendeeNoofMembers = ea.noofMembers.ToString(),
                                PricePerPerson = ev.PricePerPerson,
                                Total = (ev.PricePerPerson * ea.noofMembers).ToString()
                            };


Left outer join query:

 List<VMEvent> data = new List<VMEvent>();
var result = from ev in db.Events
                    join u in db.Users on ev.UserId equals u.UserId
                    join ea in db.EventAttendees on ev.EventId equals ea.EventId into Inners 
                    from od in Inners.DefaultIfEmpty()
                    where ev.EventDate >= startDate && ev.EventDate <= endDate
                    select new VMEvent
                    {
                        EventName = ev.EventName,
                        EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                        Place = ev.Place,
                        EventDateString = ev.EventDate.ToString(),
                        EventAttendeeNoofMembers = ea.noofMembers.ToString(),
                        PricePerPerson = ev.PricePerPerson,
                        Total = (ev.PricePerPerson * ea.noofMembers).ToString(),
                        DivisionName = u.usertype
                    };
 data = result.Distinct().ToList();


JQuery DataTable

 

JQuery DataTable  


1. Datatable binding
2. Condition base show data
3. Delete popup 
4. Data refresh after deleted data


 HTML:

<table id="myTable" class="display responsive nowrap" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Event Date</th>
                        <th>Event Name</th>
                        <th>Place</th>
                        <th>Action</th>
                    </tr>
                </thead>
            </table>


//Delete Confirmation popup
<div class="modal fade" id="myModalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title title">Delete Confirm</h4>
                </div>
                <div class="form-horizontal formppup">
                    <div id="DeleteDiv"></div>
                </div>
                <div class="form-horizontal formppup" align="center">
                    <input type="button" id="ConfirmDeleting" class="btn btn-primary" value="Yes" />
                    <input type="button" value="No" data-dismiss="modal" class="btn btn-default" />
                </div>
            </div>
        </div>
    </div>

 

 JQuery:

var table = "";
$(document).ready(function () {
    table = $("#myTable").DataTable({
        //Condition base show data
        //columnDefs : [
        //{ targets : [3],
        //    render : function (data, type, row) {
        //        return data == '12' ? 'free' : 'paid'
        //    }
        //}],
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "paging": true,
        "responsive": true,
        "ajax": {
            "type": "POST",
            "url": "EventMaster/GetJsonData",
            "dataSrc": function (data) {
                //Make your callback here.                
                if (data.value == "fail") {
                    window.location = "Unauthorised";
                } else {
                    console.log(data);
                }
                return data.data;
            }
        },
        "columns": [
                { "data": "EventDate", "name": "EventDate" },
                { "data": "EventName", "name": "EventName" }, 
                { "data": "Place", "name": "Place" }, 
                {
                    data: null,
                    orderable: false,
                    width: 100,
                    render: function (data, type, row) {
                        //console.log(data);
                        return "<a href='EventMaster/Edit/" + data.EventId + "' class='fa-icon edit' ><i class='fa fa-pencil'></i></a>"
                                + "&nbsp;<a id=" + data.EventId + " class='fa-icon delete' Onclick='fnConfirm(this);' ><i class='fa fa-trash-o'></i></a>"
                    }
                }
        ]
    });
});


function fnConfirm(model) {
    $('#myModalDelete').modal('show');
    $("#DeleteDiv").html("Are you sure you want to delete this record?");
    $("#ConfirmDeleting").click(function () {
        $.ajax({
            url: "EventMaster/DeleteData/" + model.id,
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            data: $(this).serialize(),
            success: function (data, textStatus, jQxhr) {
                $('#myModalDelete').modal('hide');
                table.ajax.reload(null, false);
            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    });
}


 

Enjoy !!!

:) 

ASP.Net - MVC C# | Report : Microsoft Reporting - Implement RDLC in MVC

 

ASP.Net - MVC C#| Report : Microsoft Reporting

- Implement RDLC in MVC



Here, I have demonstrate, how to implement Microsoft reporting in MVC web application. Please follow below steps to achieve reporting.

Step1 : Create web application with blank and select code reference "MVC". I have created project name with "DemoReport".

Step 2: Add empty controller name what you want. I have create "Home" and "Country".

Step 3: Add Entity Data Model follow screenshots.













Step 4: Add below code in Index action of Country controller
public ActionResult Index()
        {
            List<Country> countryList = null;
 
            using (DemoReportEntities db = new DemoReportEntities())
            {
 
                countryList = db.Countries.OrderBy(o=>o.CountryName).Take(10).ToList();
            }
            return View(countryList);
        }

fda


Step 5: Add below html code in Index view of Country
@model IEnumerable<DemoReport.Models.Country>
@{
    ViewBag.Title = "Country";
}
 
<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">Country List</h3>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="box-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <th>Country Name</th>
                            <th>Country Code</th>
                        </tr>
                        @foreach (var item in Model)
                        {
                            <tr>
                                <td>@Html.DisplayFor(m => item.CountryName)</td>
                                <td>
                                    @Html.DisplayFor(m => item.CountryCode)
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col-md-6">
            <div><a href="@Url.Action("GenerateReport",new {id= "PDF"})" class="btn btn-primary btn-Report"> Get Report PDF</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Excel"})" class="btn btn-primary btn-Report"> Get Report Excel</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Word"})" class="btn btn-primary btn-Report"> Get Report Word</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Image"})" class="btn btn-primary btn-Report"> Get Report Image</a></div>
        </div>
    </div>
</div>

 Step 6: Add css class in site.css or your stylesheet.
.btn.btn-primary.btn-Report {width:150px !importantmargin:3px


Step 7: Add below html code in _Layout.cshtml for menu option
<div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>
                        @Html.ActionLink("Country List""Index""Country"new { area = "" }, new { @class = "navbar-brand" })
                    </li>
                </ul>
            </div>


Step 8: Run application and it will give output as below,

 

Step 9: Add new folder in project for report, I added "Reports", then follow  below steps



 
Step 10: Add new folder in project for report data sets, I added "ReportDataSet", then follow  below steps














Step 11: Add data set to Report,




 
Step 12: Add header and footer in report


 
Step 13: Add report assembly reference in project.

Step 14: Lastly write code to generate report file in pdf, word, excel or image. create new action method in country controller and write below code.

public ActionResult GenerateReport(string id)
        {
            List<Country> data = null;
            using (DemoReportEntities db = new DemoReportEntities()){
                data = db.Countries.OrderBy(o => o.CountryName).Take(10).ToList();
            }
 
            LocalReport lr = new LocalReport();
            string path = Path.Combine(Server.MapPath("~/Reports"), "CountryReport.rdlc");
            if (System.IO.File.Exists(path)){
                lr.ReportPath = path;
            }
            else{
                return View("Index", data);
            }
 
            ReportDataSource rd = new ReportDataSource("ReportCountryDataSet", data);
            lr.DataSources.Add(rd);
            string reportType = id;
            string mimeType, encoding, fileNameExtension;
            
            string deviceInfo = "<DeviceInfo> <OutputFormat>" + id + "</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth> <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop> <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight> <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";
 
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
 
            renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, 
                out fileNameExtension, out streams, out warnings);
 
            return File(renderedBytes, mimeType);
        }

Step 15: Finally run the project and click on Generate Report button. See generated pdf.


I hope that you like the reporting tutorial.

Enjoy !!!

:)