0

Working on a web application at the moment. Need some general information on how events are declared in asp.net/javascript, and how these fit in in the code behind (c# in this case).

My own situation to which this applies is the following: I've got an AccountsTreeView, and need to update a second TreeView with information, depending on which Nodes are checked in AccountsTreeView. Since the TreeNodeCheckChanged event doesn't post a callback the (simple) solution is to implement a simple script to provide the postback. I'm just not sure how to go about catching the postback/event in my code behind.

the javascript code i found, which i would embed into my .aspx file : http://forums.asp.net/p/1109288/1888180.aspx

<script language="javascript" type="text/javascript">

function postBackByObject()
    {
        var o = window.event.srcElement;
        if (o.tagName == "INPUT" && o.type == "checkbox")
        {
            __doPostBack("","");
        } 
    }
</script>

The result I'm hoping for would be like this:

protected void TreeView_onCheckBoxChanged(Object sender, someEvent? e)
{
    e.SelectedNode.Text = "able to access the selected node.";
}

Any help would be greatly appreciated! Please excuse me for any wrongdoings in my post, it is my first one after all.

GeorgeB
  • 31
  • 6

1 Answers1

0

You can bind to javascript events by putting in your HTML onclick='postBackByObject(this)' or something similar. Here is a list of DOM events (you use the word under the "Attribute" column in code).

There are many ways to pass data from javascript to a C# method, but here is a simple example of how to using jQuery (let me know if you aren't). I prefer to bind using the on() method instead of hardcoding it into your HTML.

<script language="javascript" type="text/javascript">

$("#checkbox-id").on('click','postBackByObject');

function postBackByObject()
    {
        $.ajax({
            url: ControllerName/TreeView_onCheckBoxChanged,
            type: "POST",
            data:{sender:window.event.srcElement}
        });
    }
</script>

nice thing about on() is you can attach any event to it; it's also very dynamic and well-written.

You can then just put the [HttpPost] attribute on your C# method. Make sure it's named correctly.

I'm a little confused on why you're having your C# method be passed in the event. Do you want it to tell you what even called the method? Because you need to bind some specific event to the control (in this case, your checkbox). Surely you're not wanting to bind all events to the same method are you?

levininja
  • 3,118
  • 5
  • 26
  • 41