c# - 如何通过单击另一个gridview中的链接按钮在jquery对话框中显示Gridview

标签 c# jquery asp.net gridview

我有gridview显示BusRoute,BusNo和Action列。其中动作包含链接按钮以显示另一个gridview。我想在jquery对话框中显示它。我的代码是。

ASPX代码:

第一个Gridview:
                
                    
                        
                            
                                
                                    
                                    
                                
                                
                                    
                                    
                                    

                                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkbtn" runat="server" OnClientClick="showDialog();">Shipment Status</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>

                   </Columns>
                    </asp:GridView>
                </div>
            </div>  


第二个Gridview:

            <div class="gridview_stop"  id="popup">
                <asp:GridView ID="Stops" runat="server" AutoGenerateColumns="False" CellPadding="6" Width="190px">
                    <Columns>
                        <asp:BoundField HeaderText="Bus Stop" DataField="StopName" HeaderStyle-BackColor="#006B89">
                            <HeaderStyle BackColor="#006B89" Font-Size="18px" Font-Bold="false"></HeaderStyle>
                            <ItemStyle BackColor="#E0E0E0" HorizontalAlign="Center" />
                        </asp:BoundField>
                    </Columns>

                </asp:GridView>
            </div>


文件后面的代码:

protected void search_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter();
    con.Open();
    SqlCommand cmd = new SqlCommand("spGetRoutes", con);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@BusStop1", Source.Text);
    cmd.Parameters.AddWithValue("@BusStop2", Destination.Text);
    adapter.SelectCommand = cmd;
    adapter.Fill(ds);
    adapter.Dispose();
    cmd.Dispose();
    con.Close();
    if (ds.Tables[0].Rows.Count > 0)
    {
        Route.DataSource = ds.Tables[0];
        Route.DataBind();
        Stops.DataSource = null;
        Stops.DataBind();
        Lblmsg.Text = "";
    }
    else
    Lblmsg.Text = "No Direct Bus Between These Stop";
    Lblmsg.ForeColor = Color.WhiteSmoke;
    Route.Dispose();
    Route.DataBind();
    Stops.Dispose();
    Stops.DataBind();
}
protected void Route_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
        e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
        e.Row.ToolTip = "Click last column for selecting this row.";
    }
}


protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    string Name = Route.SelectedRow.Cells[0].Text;

    SqlDataAdapter adapter1 = new SqlDataAdapter();

    DataSet ds1 = new DataSet();
    string connetionString = "Data Source=.;Initial Catalog=BusService;uid=sa;Password=Murli@925";
    SqlConnection connection = new SqlConnection(connetionString);
    connection.Open();
    SqlCommand cmd = new SqlCommand("spGetStops", connection);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
   int BusNo= Convert.ToInt32(Name);
    cmd.Parameters.AddWithValue("@BusNo",BusNo);

    adapter1.SelectCommand = cmd;
    adapter1.Fill(ds1);
    adapter1.Dispose();
    cmd.Dispose();
    connection.Close();
    Stops.DataSource = ds1.Tables[0];
    Stops.DataBind();
}    


jQuery函数:

<script type="text/javascript">
    $("#lnkbtn").live("click",
         function showDialog() {

             $("#popup").dialog({
                 show: { effect: "fold", duration: 4000 },
                 hide: { effect: "fold", duration: 4000 },

             });
             return false;

         });

        $(document).click(function (event) {
            if (!$(event.target).closest('#popup').length) {
                if ($('#popup').is(":visible")) {
                    $('#popup').dialog('close');
                }
            }
        })

</script>


感谢和问候。

最佳答案

运行页面时,请查看呈现的html。除非您将ClientIDMode设置为“静态”,否则我怀疑您的按钮ID是$("#lnkbtn"),但更像是$("#gvWhatever_lnkbtn_0")
设置OnClientClick="showDialog();"$("#lnkbtn").live("click", function showDialog(){...})不需要两者都做。
使用服务器控制按钮激活弹出窗口通常是无效的。特别是在启用GridView行选择的情况下。我不能说您的第一个GridView是否启用了该功能,因为我只看到列表的一部分。但是发生的趋势是,您在尝试显示弹出窗口时触发了回发,因此您永远不会看到弹出窗口。
另外,您的第二个弹出窗口包含一个gridview,它需要一个数据绑定。因此,在激活弹出窗口之前,您需要确保用数据填充了gridview


在Gridview中使用jquery显示弹出窗口的两种方法:

带有2个TemplateField的GridView标记的一部分

    <asp:TemplateField HeaderText="Info">
      <ItemTemplate>
        <div>
          <div class="rs-icon rs-icon-info tooltip-marker" role="button">
          </div>
          <div id="ContactInfo" style="display:none;">
            <table id="tblContactDetail" class="ContactDetail Note">
              <tr>
                <td style="width: 80px">Name</td>
                <td style="width: 100%">
                  <asp:Literal ID="Literal1" runat="server" 
                       Text='<%# Eval("expert_name") %>' />
                </td>
              </tr>
              .
              .
              .
            </table>
          </div>
        </div>
      <ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="CV">
      <ItemTemplate>
        <div id="divButtonViewCV" runat="server" 
             class="rs-icon rs-icon-cv" role="button" 
             onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>' >
        </div>
      </ItemTemplate>
    </asp:TemplateField>


在上面的标记中,我设置了两种样式的“弹出”。第一个模板使用jQueryUI ToolTip widget,该鼠标在鼠标悬停时被激活。很好,因为它不需要单击,这意味着不必担心回发会破坏工作。有趣的是,我正在使用div作为按钮。

工作原理:带有.tooptip-marker类的div设置为激活jqueryui工具提示,该提示将通过抓住激活按钮的同级div的内部html来显示<div id="ContentInfo">的内容。请注意,此div的样式为display:none;。因此,该内容可用于工具提示,但已隐藏,因此主GridView正常显示。

为简便起见,我只包含了<div id="ContentInfo">的一部分内容。但是它确实可以包含任何东西。在我的代码中,它是一个简单的<table>,其中包含联系信息字段(使用绑定的<asp:Literal>控件),这些字段是主要GridView数据源的一部分。

但这很可能只是嵌入式GridView,它具有自己的数据源,该数据源绑定在主GridView的OnRowDatabound事件中。

以下jquery设置了小部件。有关更完整的文档,请参见jQueryUI ToolTip widget

    $( function() {
        $( document ).tooltip( {
            items: ".tooltip-marker",
            content: function() {
                return $( this ).next().html();
            },
            position: {
                my: "left top",
                at: "right+5 top-5"
            }
        } )
    } );


第二个模板字段用于激活弹出窗口。这是您必须注意回发的地方。同样,我使用了<div>样式的图标并被视为简单的按钮,因为添加了onclick

单击此按钮将显示一个弹出窗口,因此您可以查看PDF格式的个人简历。 PDF以varbinary格式存储在我们的数据库中。在这里,我使用另一个jquery插件(colorbox)将PDF显示为页面上的弹出窗口。

在下面的ViewPDF()函数中,请注意,通过设置cancelBubble = true(对于较旧的IE)或调用stopPropagation()(对于所有其他浏览器),我们可以防止click事件“冒泡”到GridView。

在此代码中,colorbox设置了iframe并将href参数传递到其src属性。我正在呼叫.ashx页面,该页面是asp通用处理程序,它使我们能够提供其他类型的内容,而无需使用标准的Web页面。可以很容易地将其配置为接受独立的.aspx页,您可以在其中放置辅助网格。

    // This plain object is used by the call to colorbox(), please 
    // refer to colorbox documentation for details.
    var colorboxDataExpertCV = {
        height: "85%",
        width: 900,
        opacity: .30,
        fixed: true,
        iframe: true,
        returnFocus: false,
        href: ''
    }

    // ========================================================
    // In the Template above, the onclick code:
    //    onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>'
    //
    // Renders to: 
    //    onclick="ViewPDF(12345)"
    //
    //  PdfHandlerExpertsCV.ashx is an GenericHandler that retrieves
    //    the CV from our database and writes the byte array to the 
    //    colorbox iframe as an "application/pdf" content type which 
    //    triggers native browser pdf management either by internal 
    //    viewer or installed PDF plugin
    // ========================================================
    function ViewPDF( p ) {
        if ( event.stopPropagation )
            event.stopPropagation();
        else
            event.cancelBubble = true;

        if ( p && p > 0 ) {
            colorboxDataExpertCV.href = "/PdfHandlerExpertsCV.ashx?cvid=" + p;
            $.colorbox( colorboxDataExpertCV );
        }
        return false;
    }


附录


  让我更明确地说,我需要将数据绑定到第二个Gridview中,
  在Jquery对话框中显示此Gridview2。此数据将被绑定并
  从对话框中的linkbutton的click事件显示在对话框中
  网格视图1


就像我在上面说的那样,您不能绑定GridView(服务器端事件),然后在不引入更多复杂性的情况下弹出一个jQuery UI对话框(客户端事件)。您必须确保准备好点击打开对话框的按钮时,弹出窗口所需的所有数据都可用。

实现此目的的最简单方法是将GridView2嵌入GridView1并同时处理所有绑定。它不是很漂亮或效率很高,并且视每个项目中显示的项目数而定,它可能会使页面变慢。但是,如果每行只有几行,那应该可以接受。


GridView2DataSource2嵌入到<ItemTemplate><TemplateField>GridView1中。
使用GridView2中的适当行字段或数据键字段将RowDataBound绑定到Gridview1GridView1事件中,然后调用GridView2.DataBind()
将元素添加到相同的TemplateField
请参考jquery dialog modal form example,其中显示了如何通过单击按钮触发对话框。在您的情况下,在示例中将第二个GridView替换为Form。


重要提示,gridview行项目ID会被“缠住”,因此您不应在jquery调用中使用id,而应使用基于元素名称和类标记的jquery选择器,即:$("button.marker")用于定义如下的按钮:

附录:2015年6月24日

CSS(<button class="marker">标记)

<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui.css" />
<script type="text/javascript" src="Scripts/jquery-2.1.4.min.js"> </script>
<script type="text/javascript" src="Scripts/jquery-ui-1.11.4.min.js"> </script>

<style>
    .btn_styling {
        text-align: center;
        width: 32px;
        margin: 2px;
        cursor: pointer;
        border: 1px solid gray;
        border-radius: 3px; 

       /* add a background image to the div 
          to make the div look like a button */ 
       /* background-image: url('...')  */
    }
    .ui-dialog-titlebar-close {
        display: none;
    }
</style>


HTML(.aspx)

<form id="form1" runat="server">
  <div style="width: 400px;">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
      DataKeyNames="user_id"
      DataSourceID="SqlDataSource1">
      <Columns>
        <asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
        <asp:TemplateField HeaderText="Info">
          <ItemTemplate>
            <div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an <img> element...anything really">X</div>
            <div style="display: none;">
              <asp:GridView ID="GridView2" runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSource2">
                <Columns>
                  <asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />
                  <asp:BoundField DataField="add_edit_date" HeaderText="Date Added" SortExpression="add_edit_date" DataFormatString='{0:dd-MMMM, yyyy}'/>
                  <asp:BoundField DataField="add_edit_by" HeaderText="Added By" SortExpression="add_edit_by" />
                </Columns>
              </asp:GridView>
              <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
                ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
                SelectCommand="SELECT email, add_edit_date, add_edit_by FROM tbl_users WHERE (user_id = @user_id)">
                <SelectParameters>
                  <asp:Parameter Name="user_id" />
                </SelectParameters>
              </asp:SqlDataSource>
            </div>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
      <RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
      SelectCommand="SELECT top 10 user_id, user_name from tbl_users">
    </asp:SqlDataSource>
  </div>
  <div id="dialogContainer">
  </div>
</form>


后台代码(VB):

Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    Dim gv2 As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
    Dim sds As SqlDataSource = DirectCast(e.Row.FindControl("SqlDataSource2"), SqlDataSource)

    sds.SelectParameters("user_id").DefaultValue = GridView1.DataKeys(e.Row.RowIndex).Value
    gv2.DataBind()
  End If
End Sub


jQuery实现对话框:

<script type="text/javascript">
    var dialogOptions = {
        autoOpen: false,
        appendTo: "#dialogContainer",
        modal: true,
        height: "auto",
        width: "auto",
        title: "Dialog Title",
        closeOnEscape: true,
        buttons: {
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        }
    };

    $( function() {
        $( ".dialog-marker" ).on( "click", function() {
            var d = $( this ).next( "div" ).first().dialog( dialogOptions );
            d.dialog( "open" );
        } );
    } );
</script>

关于c# - 如何通过单击另一个gridview中的链接按钮在jquery对话框中显示Gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30911135/

相关文章:

c# - 如何允许在 asp.net 的文本框中提交 HTML 标记?

c# - 新用户首次登录网站

c# - 如何在选项工具提示的下拉列表中使用对象属性?

javascript - Bootstrap : google map modal isn't working property when outside div class ="container-fluid" is set "height: auto"

jquery - ASP.NET 按钮 jQuery-BlockUI

asp.net - 使用 javascript 控制 gridview 列可见性

c# - 用于 C# mono 和 Unity3d 的 Consulo IDE,是否可行?

c# - Ajax 工具包不工作

jquery - 类型错误:$(...).parents(...).size 不是函数

javascript - 使用自定义请求 header 打开 URL