【问题标题】:JQUERY .show() and div tag in ASP.NETASP.NET 中的 JQUERY .show() 和 div 标记
【发布时间】:2011-04-02 18:43:55
【问题描述】:

基本上,当页面加载时,我将 div 可见性设置为 false。当我单击按钮时,我希望调用函数背后的代码,并且 div 标签是可见的,真的。

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

        });
    });


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

但是当点击按钮时,页面回发,导致div标签一直不可见。

我可以为按钮的onlclick事件设置return false,但我也需要调用该函数。

【问题讨论】:

  • 我已经添加到我对这个@user478636 的最后一个问题的回答中。您需要查看使用 Web 表单或 jQuery AJAX 中内置的 UpdatePanel / AJAX 的东西。我在最后一个问题上发布了一些链接。

标签: jquery asp.net


【解决方案1】:

如果您不希望表单提交,阻止事件的默认操作应该可以工作:

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

    } );

    evt.preventDefault();
} );


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

如果您确实希望提交表单,那么您将不得不在服务器上确定 div 是否应该在页面加载时显示(基于您的表单标准提交/验证/等)。 jQuery 只能在特定页面加载期间在页面内起作用。

【讨论】:

  • +1 虽然我的偏好是将 evt.preventDefault 作为第一个操作。
  • 感谢您的投票。如果您按照我在 Ika 的答案的评论中发布的链接,您会看到在生产代码中的函数末尾使用 preventDefault() 的建议。不过,我同意这纯粹是偏好。
  • 有兴趣我去看看。
  • @user478636 - 我不知道这是什么意思:“我的按钮正在调用函数背后的代码......”
  • 这意味着我的函数在 Product.aspx.cs 文件中。如果我停止提交按钮,则不会调用该函数。我想要显示 div 标签,以及要调用的函数!
【解决方案2】:

你必须在函数结束时返回 false。

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

在另一种情况下,提交按钮并重定向页面

【讨论】:

【解决方案3】:

看起来您已经得到了答案,但尽管您的问题对您的意图有点模糊,但这里有一些可能会有所帮助。


更新为包括 UpdatePanel 和 jQuery 解决方案

这是使用模板的 jQuery 解决方案,尽管您可以通过几种不同的方式来做到这一点。您不需要使用模板,但我可能是最简单的方法。通过仅发回 JSON,开销远小于 UpdatePanel 解决方案。

<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>

代码隐藏 - 您需要使用 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; }
}

更新面板解决方案可能对普通的 ASP.NET 更熟悉,但它的缺点是仅隐藏了回发周期。您仍然会在每个请求上发回完整的 ViewState 和 HTMl。

<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>

后面的代码

 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();

    }

【讨论】:

  • 我有一个用于搜索的文本框,我想要的是当用户单击确定按钮时,div 标签应该变得可见并显示该 div 标签内的 sql 查询的结果。这个 div 标签最初是不可见的
  • 嗯,有很多方法可以做到这一点,具体取决于您和您的团队使用的技术。我将使用 UpdatePanel 更新我的帖子,这可能是获得所需内容的最简单解决方案,但没有 AJAX 的许多好处,并且还修改现有解决方案以填补一些缺失的部分。
  • 我已经更新了答案。这是我在不知道更多的情况下所能得到的最详细的信息。
猜你喜欢
  • 1970-01-01
  • 2011-07-28
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2019-05-13
  • 1970-01-01
相关资源
最近更新 更多