views:

405

answers:

2

Hey'all

I got a li - list, one with an onclick:

<ul class="tabs"> 
    <li><a href="#tab1">Foobar_1</a></li> 
    <li onclick="doMethod"><a href="#tab2">Foobar_2</a></li> 
    <li><a href="#tab3">Foobar_3</a></li> 
    <li><a href="#tab4">Foobar_4</a></li>
</ul>

Now, the method I want to call when clicked on a tab (the li's), updates an UpdatePanel, so a gridview is shown.

I know it must have something to do with AJAX, but I ain't got a clue how to move on now...

so basically: how to call a c# method using AJAX?

+3  A: 
<li runat="server" OnClick="DoMyOnClickCall">....</li>

Then

public void DoMyOnClickCall(object sender, EventArgs e)
{
   // sender is the li dom element you'll need to cast it though.
}

To expand: (Update)

sender is an object that represents the <li>...</li> in HTML. It's called something like HtmlControl.

You'll need to cast sender to that type.

var myLI = (HtmlControl)sender;
// do stuff with `myLI`
Aren
I thought he wanted a callback not a postback
Shravan
I get a JScript runtime error... it says "DoMyOnClickCall" is undefined...well, I really got the c# method though
Joris
What exactly do you mean with "casting the li dom element"?
Joris
I've updated my answer to illustrate.
Aren
I get an invalidCastException... The ASP type object could not be cast to a HTMLControl
Joris
I don't remember the exact control that `<li>` transform into. You could find out by outputting `sender.GetType().FullName` and then you'll know.
Aren
+1  A: 

Also, you can call the method from client side by:

  1. declare your method as public static bool
  2. put attribute [WebMethod] for this method
  3. Call the method from js

Sample code:

<script language="javascript">  
    function MyClientFunction()  
    {    
    var liElement = $get("liElement").value;  
    PageMethods.doMethod(liElement,OnSuccess, OnFailure);  
    }  
    function OnSuccess(result) {  
     if(result)  
     {  
         alert("Some error message!");  
     }  
    }  
    function OnFailure(error) {  

    }
</script>
Teddy
@Teddy: I'm not sure if you had `void static` or `static bool` in your first point (based on the edit history). All I fixed was the code formatting which wasn't showing up properly when appearing after the numbered list. Add some text after it and it works. Please review in case I edited after you made an edit.
Ahmad Mageed
Thanks a lot for the formating. I meant static bool, but I'll fix it. Thanks for pointing this.
Teddy
How do I put [WebMethod] as attribute to my c# method? Do I need a special reference?
Joris
It is declared in `[System.Web.Services.WebMethod]`. You can find more information here http://msdn.microsoft.com/en-us/library/byxd99hx(VS.71).aspx
Teddy