1

Basically, when the page loads i set the div visibility to false. When i click the button, i want the code behind function to be called, and the div tag to be visible, true.

    $('#Button2').click(function () {
        $('#edit').show(function () {

        });
    });


    <input type="submit" id="Button2" runat="server" value="Search" OnServerClick="Button1_Click" />

but when clicking the button, the page posts back, causing the div tag to be invisible all times.

I can set the return false to the onlclick event of the button , but i need to call the function also.

user478636
  • 3,304
  • 15
  • 49
  • 76
  • possible duplicate of [JQUERY .show() function in ASP.NET](http://stackoverflow.com/questions/5524891/jquery-show-function-in-asp-net) – Kevin LaBranche Apr 02 '11 at 18:54
  • I've added to my answer from the last question for this @user478636. You need to look at using the UpdatePanel / AJAX stuff built into web forms or jQuery AJAX. I posted some links on the last question. – Kevin LaBranche Apr 02 '11 at 19:09

3 Answers3

1

If you don't want the form to submit, preventing the default action of the event should work:

$('#Button2').click(function ( evt )
{
    $('#edit').show(function ()
    {

    } );

    evt.preventDefault();
} );


<input type="submit" id="Button2" runat="server" value="Search" OnServerClick="Button1_Click" />

If you do want the form to submit, then you are going to have to figure out on the server whether the div should or should not be showing at page load (based on your criteria of form submission/validation/etc). jQuery can only act within the page for the duration of a particular page load.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • +1 although my preference is to put the evt.preventDefault as the first action. – Nicky Waites Apr 02 '11 at 18:58
  • Thanks for the vote. If you follow the link I posted in the comment to Ika's answer, you'll see advice there to use `preventDefault()` at the end of the function in production code. Purely preference, though, I agree. – JAAulde Apr 02 '11 at 18:59
  • Interesting I'll take a look. – Nicky Waites Apr 02 '11 at 19:04
  • @user478636 - I don't know what this means: "my button is calling a code behind function..." – JAAulde Apr 02 '11 at 19:06
  • it means my function is in the Product.aspx.cs file. if i stop my button from submitting, the function wont be called. i want the div tag to display, and the function to be called! – user478636 Apr 02 '11 at 19:07
  • @user478636 - see the paragraph I added to my answer. You are operating outside the realm of jQuery with what you want. – JAAulde Apr 02 '11 at 19:10
1

you must return false at the end of the function.

$('#Button2').click(function () {
   ...some code
   return false
});

in another case button is submitted and page redirected

  • `return false` is too broad an operation. Check out http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ – JAAulde Apr 02 '11 at 18:51
0

Looks like you got your answer but here is something that might help although your question is a little bit vague on what your intent is.


Updated to include UpdatePanel and jQuery solutions

This is the jQuery solution using templates although you could do this in a few different ways. You don't need to use templates but I might it the easiest way of doing this. By sending back only JSON the overhead is much smaller than the UpdatePanel solution.

<script src="https://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.min.js" type="text/javascript"></script>

<script id="productTemplate" type="text/html">
    <tr>
        <td>${Name}</td><td>${Price}</td> 
    </tr>
</script>

<script type="text/javascript">

    $(function () {

        $("#searching").ajaxStart(function () {
            $(this).show();
        });

        $("#searching").ajaxStop(function () {
            $(this).hide();
        });

        $("#btnSearch").click(function (evt) {

            // JSON.stringify requires json2.js for all browser support
            //https://github.com/douglascrockford/JSON-js

            //post to WebMethod
            var p = { product: $("#product").val() };
            $.ajax({
                type: "POST",
                url: "Default.aspx/Search",
                data: JSON.stringify(p),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                   //unwrap response if using .NET 3.5+ 
                   var results = data.d;

                   //jQuery templates make it much easier to render repeat data
                    $("#productTemplate").tmpl(results).appendTo($("#products").empty());
                    $("#results").show('slow');
                }
            });

            evt.preventDefault();
        });

</script>

html

<div id="searching" style="display:none;">
    Searching Please Wait....
    <img src="Products/ajax-loader.gif" alt="Searching" />
</div>
<input type="text" id="product" />
<input type="submit" id="btnSearch" value="Search" />

<div id="results" style="display:none;">
    <table cellspacing="0" border="1" style="border-collapse:collapse;">
        <tbody><tr><th scope="col">Product</th><th scope="col">Price</th></tr></tbody>
        <tbody id="products"></tbody>
    </table>
</div>

Code behind - you will need to include using System.Web.Services;

//If you're going to be using this in multiple locations then I'd put this into a seperate WebService.asmx
[WebMethod]
public static List<Product> Search(string product)
{

    //Simulate database call
    System.Threading.Thread.Sleep(2000);

    //Do your database code here

    //Using strongly typed model makes generating the JSON much easier
    var products = new List<Product>();

    for (int i = 0; i < 10; i++) {
        products.Add(new Product() { Name = String.Format("Product {0} {1}", product, i), Price = 10 * i });
    }

    return products;
}

public class Product
{
    public string Name { get; set; }
    public int Price { get; set; }
}

Update Panel Solution is probably more familiar to normal ASP.NET but it has the disadvantage of just hiding the Postback cycle. You are still sending back the full ViewState and HTMl on each request.

<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>

<!-- Grab a nice loading gif http://www.ajaxload.info/ -->
<asp:UpdateProgress ID="MainUpdateProgress" runat="server" 
    AssociatedUpdatePanelID="MainUpdatePanel">
    <ProgressTemplate>
        Searching Please Wait....
        <img src="ajax-loader.gif" alt="Searching"/>
    </ProgressTemplate>
</asp:UpdateProgress>

<asp:UpdatePanel ID="MainUpdatePanel" runat="server">

<ContentTemplate>
<asp:TextBox id="tbProduct" runat="server" />
<asp:Button ID="btnSearch" runat="server" Text="Search Products" 
        onclick="btnSearch_Click" />


<asp:GridView ID="grdvProducts" runat="server"></asp:GridView>

<br />

<!-- if you dont want to use a gridview then a repeater will do -->
<asp:Repeater ID="rProducts"  runat="server">
    <HeaderTemplate>
        <table cellspacing="0" border="1" style="border-collapse:collapse;">
        <tbody>
        <tr><th scope="col">Product</th><th scope="col">Price</th></tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr><td><%# Eval("Product") %></td><td><%# Eval("Price") %></td></tr>
    </ItemTemplate>
    <FooterTemplate>
        </tbody>
        </table>
    </FooterTemplate>
</asp:Repeater>

</ContentTemplate>

</asp:UpdatePanel>

Code behind

 protected void btnSearch_Click(object sender, EventArgs e)
    {

        //Do Validation
        string product = tbProduct.Text;

        //Do database calls here
        Thread.Sleep(2000); //Simulate long search time

        var dt = new DataTable();
        dt.Columns.Add("Product");
        dt.Columns.Add("Price");

        for (int i = 0; i < 10; i++) {
            dt.Rows.Add(String.Format("Product {0} {1}", product, i), i * 10);
        }

        grdvProducts.DataSource = dt;
        grdvProducts.DataBind();

        rProducts.DataSource = dt;
        rProducts.DataBind();

    }
Nicky Waites
  • 2,428
  • 18
  • 19
  • i have a textbox for searching, what i want is that when the user clicks the ok button, the div tag should become visible and show the results from a sql query inside that div tag. this div tag is initally not visible – user478636 Apr 03 '11 at 06:02
  • Well there are lots of ways of doing that depending on which techniques you and your team are comfortable using. I'll update my post with using an UpdatePanel which is probably the easiest solution to get what you want but without many of the benefits of AJAX and also modify the existing solution to fill in some of the missing pieces. – Nicky Waites Apr 03 '11 at 08:59
  • I've updated the answer. That is about as detailed as I can get without knowing more. – Nicky Waites Apr 03 '11 at 11:09