Showing posts with label webform. Show all posts
Showing posts with label webform. Show all posts

Tuesday, October 30, 2012

Export HTML to excel using jQuery and asp.net

Here we will see how to export a HTML table content to excel using asp.net web form and C# using jQuery.

Let’s start with a small piece of code –
    <h2>
        Export to excel using jquery
    </h2>

    <a href="#" class="expToExcel">Export to excel</a>
    <div id="toReport">
    <table>
        <tr>
          <th>Name</th>
          <th>Age</th>
          <th>Email</th>
        </tr>
        <tr>
          <td>John</td>
          <td>44</td>
          <td>john@gmail.com</td>
        </tr>
        <tr>
          <td>Rambo</td>
          <td>33</td>
          <td>rambo@gmail.com</td>
        </tr>
        <tr>
          <td>It's hot</td>
          <td>33</td>
          <td>test@hotmail.com</td>
        </tr>
    </table>
    </div>
On click of "Export to excel" let do export the content to excel file using jQuery. We can do this in following steps-
  1. Get the HTML content.
  2. Encode the HTML content.
  3. Pass the HTML encoded content to an aspx page.
  4. Generate the excel file from code behind.
Step 1-
var data = $("#toReport").html();
data = escape(data);
Why we are escaping the HTML data and then passing to code behind. Answer is that we are going to pass the data to an aspx page using a dynamically created form. It is going to through "A potentially dangerous Request.Form value was detected from the client" error. That’s why we are escaping the HTML content.

Step 2-
$('body').prepend("<form method='post' action='exportPage.aspx' style='top:-3333333333px;' id='tempForm'><input type='hidden' name='data' value='" + data + "' ></form>");
$('#tempForm').submit();
$("tempForm").remove();
In this step we are adding an aspx page named exportPage.aspx. And creating a form tag on the fly, add the HTML data to a hidden field and submit the form using jQuery. And finally remove the added form tag.

Step 3 & 4-
        string data = Request.Form["data"];
        data = HttpUtility.UrlDecode(data);
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=report.xls");
        Response.Charset = "";
        Response.ContentType = "application/excel";
        HttpContext.Current.Response.Write( data );
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
In this step we are simply creating the excel file and flushing the result as excel. You may see a message saying corrupt excel file do you want to open the file. You can open the file not an issue. I am too lazy to fine out proper setting.

You can also download the code from here.

Wednesday, June 13, 2012

Passing extra parameters with dataTable.net plugin while server paging is enabled in asp.net MVC 3 and Web form

Recently I have added two posts to implement dataTable.net jQuery plugin with server side paging with MVC3 and asp.net web form. First one is in MVC 3 and second one is in web form. We can find these two posts here-

http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet.html
http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet_06.html

I will request to study these two posts in sequentially to understand this one.

In this post we will be discussing how to pass additional parameters when page index changes happen in dataTable.net. To pass additional parameters in ajax paging we can use fnServerParams function of dataTable. In the MVC post we have discussed how dataTable plugin adds request parameters as querystring. And this function (fnServerParams) provides an input parameter which is nothing but an array of the query string parameters. We can do modification to the array in the function to accomodiate our need of extra parameters. Each array element in the input array is an object of the following form-
{ "name": "name of parameter/querystring", "value": "value of parameter/querystring " }
So, we can add our additional parameter accordingly. Suppose we have following input data as additional parameter-
First Criteria: <input id="txtParameter1" /><br />
Second Criteria : <input id="txtParameter2" />
We can add the these extra parameter like below-
<script type="text/javascript" charset="utf-8">
    $(document).ready(function () {
        $('#example').dataTable({
            "bServerSide": true,
            "bProcessing": true,
            "sPaginationType": "full_numbers",
            "sAjaxSource": 'Datatable Plugin Pagination Issue AjaxPath.aspx',
            "fnServerParams": function (aoData) {
                aoData.push(
                    { "name": "firstcriteria", "value": $("#txtParameter1").val() },
                    { "name": "secondcriteria", "value": $("#txtParameter2").val() }
                );
            }
        });
    });
</script>
In web form:

In web form we can access these parameters like below and use for database operations –
var firstCriteria = Request.QueryString["firstcriteria"];
var secondCriteria = Request.QueryString["secondcriteria"];
In MVC 3-

To use in MVC 3 we can modify data model like below to accommodate our new parameters-
    public class TableParameter
    {
        public string sEcho { get; set; }
        public int iDisplayStart { get; set; }
        public int iDisplayLength { get; set; }
        public string firstcriteria { get; set; }
        public string secondcriteria { get; set; }
    }
Input data will be available in the controller method to use.

Wednesday, June 6, 2012

Ajax data paging with dataTables.net jQuery plugin in asp.net web form

I have recently added a post on calling ajax data to dataTables.net jQuery plugin with asp.net MVC 3. You can refer the following post-

http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet.html

I will suggest to study the above post before proceeding this post. But the approach does not work with web form. So, how to do it with web form. As per my knowledge ajax paging with dataTable.net does not work properly with pagemethod or web service. We can solve this with an aspx page directly. But please take care of the security constraints as per your requirement.

First add a aspx page separate from your previous page. And change the sAjaxSource of the dataTable plugin like-
"sAjaxSource": 'Datatable Plugin Pagination Issue AjaxPath.aspx'
And in page load of the page use the following code-
public partial class Datatable_Plugin_Pagination_Issue_AjaxPath : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var data = new[]{   
                new []{"Trident test","Internet Explorer 4.0","Win 95+","4","X"},
                new []{"Trident","Internet Explorer 5.0","Win 95+","5","C"},
                new []{"Trident","Internet Explorer 5.5","Win 95+","5.5","A"},
                new []{"Trident","Internet Explorer 6","Win 98+","6","A"},
                new []{"Trident","Internet Explorer 7","Win XP SP2+","7","A"},
                new []{"Trident","AOL browser (AOL desktop)","Win XP","6","A"},
                new []{"Gecko","Firefox 1.0","Win 98+ / OSX.2+","1.7","A"},
                .
                .
                .
                .
                new []{"Other browsers","All others","-","-","U"}
            };
        var pagedData = data.Skip(int.Parse(Request.QueryString["iDisplayStart"])).Take(int.Parse(Request.QueryString["iDisplayLength"]));
        System.Web.Script.Serialization.JavaScriptSerializer toJSON = new System.Web.Script.Serialization.JavaScriptSerializer();
        Response.Clear();
        string dataString = toJSON.Serialize(new
        {
            sEcho = Request.QueryString["sEcho"],
            iTotalRecords = data.Count(),
            iTotalDisplayRecords = data.Count(),
            aaData = pagedData
        });
        Response.Write(dataString);
        Response.End();
    }
}
That's all. Problem solved.