1

I am working on asp.net website and I have Imagebutton that call c# function on click event. I want to prevent this image button from creating a postBack.

I have tried adding

OnClientClick="return false;" and UseSubmitBehavior="false"

but it didn't work for me.

Do you have a solution?

I tried to call the server function through client side function as the following, but it seems there is something wrong with my code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>


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

        $.ajax(
            {

                type: "POST",
                url: "BerthOccupancyForm.aspx/GridToExcel",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",

            });

        return false;
    });

</script>

enter image description here

This is code behind:

[WebMethod()]   
public static void GridToExcel(GridView berthGridView, GridView recap)
{
    if (berthGridView.Rows.Count > 0)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
        HttpContext.Current.Response.ContentType = "text/csv";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        berthGridView.RenderControl(htw);

        if (RT == "Year To Date")
        {
            foreach (GridView gv in Code)
            {
                gv.RenderControl(htw);
            }
        }
        else
        {
            recap.RenderControl(htw);

        }

        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();
    }
}

Thanks

Mai Shibuya
  • 37
  • 1
  • 2
  • 8
  • have you written on `page_load` for that button in server side ? Also show the full aspx of the **ImageButton** – Nad Mar 02 '16 at 09:51
  • 1
    If it is webforms you have to deal with postbacks on the serverside controls. Other way you just can't call the OnClick-Function. But you still always can switch to AJAX or just replace the ImageButton to simple image and call JS-Code that calls a Web-Method(which is basicaly another way to do AJAX-Like actions) – Lorin Mar 02 '16 at 10:12
  • @coder i did write it in the page-load as well but it didn't work for me. – Mai Shibuya Mar 02 '16 at 11:03
  • @Lorin i tried to use WebMethod. however, it requires the method to be static and i get errors in the method. Do you have an example? – Mai Shibuya Mar 02 '16 at 12:09
  • @MaiShibuya yes, it should be static. And this is a bit deprecated way to do this. But it still works. Look into this two pages: http://stackoverflow.com/questions/6928533/calling-a-webmethod-with-jquery-in-asp-net-webforms http://www.c-sharpcorner.com/UploadFile/dacca2/static-webmethod-in-code-behind-webform/ – Lorin Mar 03 '16 at 09:08
  • @Lorin i tried to do the same example as you sent me, but, still the gridviewlist is still empty. can you check me code if it is possible? – Mai Shibuya Mar 03 '16 at 11:13
  • @MaiShibuya could you plz edit your post and add text from .aspx and .aspx.cs or post it as a GIST on github(https://gist.github.com/) and add a link to it there so i can take a look into it. – Lorin Mar 03 '16 at 12:12
  • @Lorin i've edited my post. Thanks – Mai Shibuya Mar 03 '16 at 12:32
  • why are you using an ImageButton if you don't want a postback? Why not just use a standard normal image? – Ahmed ilyas Mar 03 '16 at 12:34
  • did you try this? ` $('#excelImageButton').click(function(e) {e.preventDefault()})` – Pavan Teja Mar 03 '16 at 12:36
  • @Ahmedilyas yeah i know that a nomal image doesn't cause a postback. But i was trying if there is s way for an imagebutton to not cause a postback by using AJAX or other method. – Mai Shibuya Mar 03 '16 at 12:37
  • @PavanTeja $('#excelImageButton').click(function (e) { e.preventDefault() $.ajax( { type: "POST", url: "BerthOccupancyForm.aspx/GridToExcel", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", }); return false; }); is it like this? – Mai Shibuya Mar 03 '16 at 12:40
  • check this [fiddle](https://jsbin.com/vuvaguyaxe/edit?js,output) – Pavan Teja Mar 03 '16 at 12:42
  • @PavanTeja i want to tell you that my method has two parameters of type gridview. and i am not sure where to add them in the function since i'm very beginner in ajax and jquery – Mai Shibuya Mar 03 '16 at 12:46
  • where are those gridviews?it will be very helpfill if you can share the aspx page – Pavan Teja Mar 03 '16 at 12:48
  • @PavanTeja i have added a link for the image under the ajax code in this post. Thanks. – Mai Shibuya Mar 03 '16 at 12:53
  • Did you try any of the tricks given here: http://stackoverflow.com/questions/2703267/can-i-create-an-asp-net-imagebutton-that-doesnt-postback – ConnorsFan Mar 03 '16 at 12:59
  • you can put it inside an update panel so it doesn't cause a full page postback but only a partial postback to the server. but if you are talking about using client side AJAX call to a custom method then that is a little more involved. you certainly need to set the e.preventDefault() I believe - something like this: http://stackoverflow.com/questions/16710561/prevent-linkbutton-post-back-onclientclick-not-working-why – Ahmed ilyas Mar 03 '16 at 13:03
  • @ConnorsFan yes i did it gives Javascript error – Mai Shibuya Mar 03 '16 at 13:07
  • what error did you get? – Pavan Teja Mar 03 '16 at 13:08
  • @PavanTeja thie error 0x800a1391 - JavaScript runtime error: 'my' is undefined – Mai Shibuya Mar 03 '16 at 13:12
  • There were many different answers in the link that I gave. If the accepted answer does not work, maybe one of the other does. One answer sets the PostBackUrl to do nothing. – ConnorsFan Mar 03 '16 at 13:43
  • ... like this: – ConnorsFan Mar 03 '16 at 13:52

2 Answers2

0

first of all,you cant pass gridview to webmethod.

if you seriously want to export the grid to excel use client side library to generate excel from table markup or do a partial postback and generate excel and write to response.

see this plunker to export to excel in javascript.

Pavan Teja
  • 3,192
  • 1
  • 15
  • 22
0

Thank you guys for your suggestions. I was able to solve it this way.

I have added a static class that has static List and static string. And i call this Class in the WebForm. This way keep the data of GridViews during the PostBack

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
/// <summary>
/// Summary description for Global
/// </summary>
public static class Global
{

    public static List<GridView> GridViewList = new List<GridView>();
    public static string ReportType = "";
}

The following C# Function exports to excel using the data from the static Class.

public  void GridToExcel()
{
    if (berthOccupancyDataGridView.Rows.Count > 0)
    {
        Response.Clear();
        //HttpContext.Current.Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
        //HttpContext.Current.Response.Charset = "";
        Response.ContentType = "text/csv";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        berthOccupancyDataGridView.RenderControl(htw);

        if (Global.ReportType == "Year To Date")
        {
            foreach (GridView gv in Global.GridViewList)
            {
                gv.RenderControl(htw);
            }
        }
        else if(Global.ReportType == "Monthly")
        {
            recapGridView.RenderControl(htw);

        }

        Response.Write(sw.ToString());
        Response.End();
    }
}
Mai Shibuya
  • 37
  • 1
  • 2
  • 8