holyredbeard
holyredbeard

Reputation: 21208

trigger jQuery event from code behind file (asp.net)

I'm working on an simple application which shows a list of contacts from a db. It's possible to add new contacts to the db, and if a new contact is successfully added a message telling so is visible.

The place is shown in a label inside a div which by default is set to Visible=false. When a contact is successfully added Visible is set to true and a message is shown in the labels text. So far so good.

The thing is that I want the message to disappear after 10 seconds, and for doing that I want to use jQuery. What I need help with is how to trigger the jQuery function from the code behind file. I've tried to check if the element exists and if so fire the function, but nothing happens.

Thanks in advance!

from code behind:

protected void ContactObjectDataSource_Inserted(object sender, ObjectDataSourceStatusEventArgs e) {
        if (e.Exception != null) {
            AddErrorMessage("An error occurred.");
            e.ExceptionHandled = true;
        }
        else {
            successMessage.Visible = true;
            message.Text = "The contact was successfully added!";
        }
    }

from default.aspx:

    <div id="successMessage" runat="server" visible="False">
            <asp:Label ID="message" runat="server"></asp:Label>
    </div>

from the js-file:

var Capsule = {

    hideMessage: function () {
        setTimeout(function() {
                $("#successMessage").hide("fade", {}, 1000);
        }, 5000);
    }
}

window.onload = Capsule.init;

Upvotes: 0

Views: 1762

Answers (2)

Murtaza
Murtaza

Reputation: 3065

Hi here for doing this you can use Ajax.dll and create the Ajax.Method.

Note: but cannot use any serverside control in this method. you need to pass the values in your method and also display your out message on client side. returning false will not postback you page as well.

refer to the below section for practical implementation.

Refer this link.

Upvotes: 0

Vikram
Vikram

Reputation: 8333

you can use the following code to call the jquery function from c#:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>hideMessage();</script>", false);

Upvotes: 1

Related Questions