Innat3
Innat3

Reputation: 3576

Unable to run C# method and avoid postback when I click on my ImageButton

I have the following ImageButton, which toggles the visibility property of a calendar control.

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/calendar.png" OnClick="Display_Calendar1"/>

Problem is, when I click on it, it sends a postback command which conflicts with some of my other code. I've seen there are multiple threads about this where the most common solution is to call "return false;" on the OnClick event. However, I still need to run the calendar toggle method:

//cStart_Date is the calendar control and tbStart_Date is a textbox where I write down the chosen date.
protected void Display_Calendar1(object sender, ImageClickEventArgs e)  
{
    if (IsValidDate(tbStart_Date.Text))
    {
        cStart_Date.SelectedDate = Convert2Date(tbStart_Date.Text);
        cStart_Date.VisibleDate = cStart_Date.SelectedDate;
    }
    cStart_Date.Visible = !cStart_Date.Visible;
}

In all the examples I've seen, the function ran before the "return false;" is a JavaScript function, but I want it to run my C# method. This results in a Server error when I launch it on the browser, displaying Compiler Error Message: CS1026:) expected

I've also tried the method without arguments protected void Display_Calendar1() but the result is the same...

Upvotes: 1

Views: 96

Answers (2)

Innat3
Innat3

Reputation: 3576

Okay apparently you cannot avoid the postback when execute the server side Click event. An updatePanel will minimize the rendering load and minimize page flickering but there will still be a postback call, thus defeating my purpose. I guess doing it with javascript on the client side is the only way.

Upvotes: 0

Vicky_Burnwal
Vicky_Burnwal

Reputation: 981

Toggling of calendar control can also be done through java script. You need to use OnClientClick property of Image button.

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/calendar.png" OnClientClick="ToggleCalendar"/> 

<script>
function ToggleCalendar() {
    var clndr= document.getElementById('cStart_Date');
    clndr.style.display = (clndr.style.display == 'none') ? 'block' : 'none';
}
</script>

You can perform validation or other stuffs as well in Java script funtion.

Upvotes: 1

Related Questions