Skip to content Skip to sidebar Skip to footer

Executing Server-side Methods By Clicking On A Div

I'm working on an ASP.Net project, with C#. Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat='server' form.

Solution 1:

You will have to handle the click in the div using the Jquery and call server-side methods through JQuery

Solution 2:

There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code. Here is the handler version:

 $("#btn1").click(function() {
    $.ajax({
            url: '/Handler1.ashx?param1=someparam',
            success: function(msg, status, xhr) {
                //doSomething, manipulate your html
            },
            error: function() {  
             //doSomething
            }
        });
 });

I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.

Handler:

publicclassHandler1: IHttpHandler
{
   publicvoidProcessRequest(HttpContext context)
   {
      context.Response.ContentType = "application/json";
      var param1= context.Request.QueryString["param1"];
      //param1 value will be "someparam"// do something cool like filling a datatable serialize it with newtonsoft jsonconvertvar dt= new DataTable();
      // fill it
      context.Response.Write(JsonConvert.SerializeObject(dt));
   }
}

If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.

Solution 3:

You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()

Solution 4:

Add this code in your jquery on div onclick and pass DIv id whcih call click

__doPostBack('__Page', DivID);

On page load add this code

if (IsPostBack)
            {
    //you will get id of div which called function
    string eventargs = Request["__EVENTARGUMENT"];

                    if (!string.IsNullOrEmpty(eventargs))
                    {
                       //call your function 
                    }
}

Solution 5:

Make the div runat="server" and id="divName"

in page_Load event in cs:

if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
    //code to run in click event of divName
}
}

divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));

Hope it helps :)

Post a Comment for "Executing Server-side Methods By Clicking On A Div"