无法获取模态JQuery窗口来更新对数据库的更改

时间:2016-05-25 19:15:08

标签: jquery asp.net popup modal-dialog

我在这个问题上度过了一整天,而且我很难过。 我有一个名为“singlecards.aspx”的网页,其中包含一个从数据库填充的GridView控件,它工作正常。这是该文件的代码:

SingleCard.aspx

<%@ Page Title="SRN - Edit Single Card Records" Language="C#"   MasterPageFile="~/TVS_Main.master" AutoEventWireup="true" CodeFile="SingleCards.aspx.cs" Inherits="Accounts_TVS_SingleCards" %>

<asp:Content ID="Content1" ContentPlaceHolderID="serverHead" runat="server">
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript"
        src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js"></script>
    <link type="text/css" rel="stylesheet"
        href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/smoothness/jquery-ui.css" />
    <script language="text/javascript">
        function __doPostBack(eventTarget, eventArgument) {
            document.Form1.__EVENTTARGET.value = eventTarget;
            document.Form1.__EVENTARGUMENT.value = eventArgument;
            document.Form1.submit();
        }
    </script>
    <script type="text/javascript">
    $(document).ready(function () {
        $('a.popup').live('click', function (e) {

            var page = $(this).attr("href")

            var $dialog = $('<div></div>')
            .html('<iframe style="border:0px; " src = "' + page + '" width=600px" height="100%"></iframe>')
            .dialog({
                autoOpen: false,
                modal: true,
                height: 550,
                width: 'auto',
                title: "Message Details",
                buttons: {
                    "Close": function () { $dialog.dialog('close'); }
                },
                close: function (event, ui) {
                    __doPostPack('<%= btnRefresh.ClientID %>', '');
                }
            });
            $dialog.dialog('open');
            e.preventDefault();
        });
    });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ctMain" runat="server">
    <h1>Manage Single Card Definitions</h1>
    <br />
    <asp:ScriptManager ID="sm" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
    <asp:UpdateProgress ID="updProgress" runat="server">
        <ProgressTemplate>
            <img src="../../images/loading.gif" alt="" />
        </ProgressTemplate>
    </asp:UpdateProgress>
    <asp:UpdatePanel ID="pnlCards" runat="server">
        <ContentTemplate>
            <div class="spantwo">
                <h2>Currently Defined Card Records</h2>
                <asp:ObjectDataSource ID="objCards" runat="server" EnableViewState="false"
                    MaximumRowsParameterName="maxRows" EnablePaging="true" SortParameterName="orderBy"
                    SelectCountMethod="GetCount" SelectMethod="GetList" StartRowIndexParameterName="startRow"
                    TypeName="SRN.Data.SingleCardDB" DataObjectTypeName="SRN.Data.SingleCard"></asp:ObjectDataSource>
                <asp:GridView ID="gvCards" runat="server" AllowPaging="true" DataKeyNames="CardID" PageSize="10"
                    DataSourceID="objCards" AllowSorting="true" AutoGenerateColumns="false" CssClass="grid"
                    ToolTip="Definitions of Single Tarot Cards"
                    EnableSortingAndPagingCallbacks="true" OnRowCommand="gvCards_RowCommand">
                    <HeaderStyle CssClass="grid_header"></HeaderStyle>
                    <RowStyle CssClass="grid_rowstyle"></RowStyle>
                    <SelectedRowStyle CssClass="grid_selectedrowstlye"></SelectedRowStyle>
                    <AlternatingRowStyle CssClass="grid_alternatingrowstyle"></AlternatingRowStyle>
                    <EmptyDataTemplate>
                        <center>
                        <span class="darkred">No data to display at this time.</span>       
                    </center>
                    </EmptyDataTemplate>
                    <Columns>
                        <asp:BoundField DataField="CardName" HeaderText="Card Name" SortExpression="CardName" />
                        <asp:CheckBoxField DataField="IsActive" HeaderText="Active" SortExpression="IsActive"
                            ItemStyle-HorizontalAlign="Center" />
                        <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <a class="popup" href='editsinglecard.aspx?CardID=<%# Eval("CardID") %>'>Edit</a>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:ButtonField ButtonType="Button" CommandName="EditMeanings" Text="Meanings" ControlStyle-CssClass="gridbutton"
                            ItemStyle-HorizontalAlign="Center"></asp:ButtonField>
                    </Columns>
                </asp:GridView>
                <p></p>
                <asp:Button ID="btnRefresh" runat="server" Text="Refresh Records" OnClick="btnRefresh_Click" CssClass="button"></asp:Button>
                <br />
                [<a class="popup" href="editsinglecard.aspx">Add New Card</a>]
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    <br />
    <hr />
    <p></p>
    <div class="dataentry">
        <div class="spantwo">
            [<a class="button" href="clienthome.aspx" title="Return To Main Page">Back To Main Page</a>]
        </div>
    </div>
</asp:Content>

该页面显示数据库记录的GridView。其中一个字段是一个模板字段,其中包含一个链接,该链接调用JQuery脚本以打开弹出窗口以显示要编辑的记录。该页面的代码EditSingleCard.aspx在这里(首先是.aspx文件然后是代码隐藏):

EditSingleCard.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="EditSingleCard.aspx.cs" Inherits="Accounts_TVS_EditSingleCard" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Edit Card Definition</title>
    <link rel="stylesheet" type="text/css" href="../../styles/tarotverbatim_main.css" />
</head>
<body class="body_whiteBG">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server" />
    <asp:UpdatePanel ID="updCard" runat="server">
        <Triggers>
            <asp:PostBackTrigger ControlID="btnUpdate" />
        </Triggers>
        <ContentTemplate>
            <h2>Add/Edit Card Definition</h2>
            <br />
            <table class="table_small">
                <tr>
                    <td class="table_td_leftcol">
                        <span class="formlabel">Card Name :</span>
                    </td>
                    <td class="table_td_rightcol">
                        <asp:TextBox ID="tbCardName" runat="server" Width="95%" MaxLength="64"
                            ToolTip="Name you wish to use as an internal reference"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfCardName" runat="server"
                            ControlToValidate="tbCardName" CssClass="darkred" Text="*"
                            ErrorMessage="'Card Name' is required.">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="table_td_leftcol">
                        <span class="formlabel">Name Seen By Users:</span>
                    </td>
                    <td class="table_td_rightcol">
                        <asp:TextBox ID="tbConsumerTitle" runat="server" Width="95%" MaxLength="64"
                            ToolTip="What will the users see as this card's name?"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfConsumerTitle" runat="server"
                            ControlToValidate="tbConsumerTitle" CssClass="darkred" Text="*"
                            ErrorMessage="'Consumer Title' is required.">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="table_td_leftcol">
                        <span class="formlabel">Card Image File :</span>
                    </td>
                    <td class="table_td_rightcol">
                        <asp:FileUpload ID="ctlImage" runat="server" AllowMultiple="false"
                            ToolTip="Image file to associate with this card"></asp:FileUpload>
                    </td>
                </tr>
                <tr>
                    <td class="table_td_leftcol">
                        <span class="formlabel">Is Record Active? :</span>
                    </td>
                    <td class="table_td_rightcol">
                        <asp:CheckBox ID="chkActive" runat="server"></asp:CheckBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" class="table_td_spantwo">
                        <asp:Button ID="btnUpdate" runat="server" CssClass="button"
                            Text="Save/Update" OnClick="btnUpdate_Click"></asp:Button>
                        <asp:Button ID="btnCancel" runat="server" CssClass="button"
                            Text="Cancel" OnClick="btnCancel_Click" CausesValidation="false"></asp:Button>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" class="table_td_spantwo">
                        <asp:ValidationSummary ID="vsCard" runat="server"
                            CssClass="darkred"
                            HeaderText="Please correct the following :"></asp:ValidationSummary>
                    </td>
                </tr>
          </table>
          <br />
          <asp:Label ID="lblStatus" runat="server" ViewStateMode="Disabled"></asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>
</body>
</html>

代码隐藏是这样的:

EditSingleCard.aspx.cs

   using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SRN.Data;
using SRN.Web;
using System.IO;
using SRN.IO;

public partial class Accounts_TVS_EditSingleCard : SRN.Web.SRNBasePage
{
    static string cardID;
    static SingleCard card;
    static bool isNew;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ClearFields();
        }
        LoadCardInfo();
    }


    void LoadCardInfo()
    {
        if (Request.QueryString["CardID"] == "")
        {
            isNew = true;
            return;
        }
        cardID = Request.QueryString["CardID"];
        card = SingleCardDB.Get(cardID);

        if (!String.IsNullOrEmpty(card.CardID.ToString()))
        {
            isNew = false;
            tbCardName.Text = card.CardName;
            tbConsumerTitle.Text = card.ConsumerTitle;
        }
    }

    void ClearFields()
    {
        tbCardName.Text = "";
        tbConsumerTitle.Text = "";
        lblStatus.Text = "";
        chkActive.Checked = true;
        card = new SingleCard();
    }


    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (isNew && !ctlImage.HasFile)
            {
                lblStatus.CssClass = "darkred";
                lblStatus.Text = "You must select an image file to associate with this card.";
                return;
            }
            card.CardImageFile = (!isNew ? "N/A" : ctlImage.FileName.ToString());
            if (card.CardID.Length == 0)
                card.CardID = Guid.NewGuid().ToString();
            card.CardName = Helpers.ProperCase(tbCardName.Text);
            card.ConsumerTitle = tbConsumerTitle.Text;
            card.IsActive = chkActive.Checked;
            bool success = SingleCardDB.Add(card);
            if (success)
            {
                PostImage();
                isNew = false;
                cardID = card.CardID;
                lblStatus.CssClass = "darkgreen";
                lblStatus.Text = "Record saved successfully.";
            }
            else
            {
                lblStatus.CssClass = "darkred";
                lblStatus.Text = "Unable to post record at this time.";
            }
        }
    }


    void PostImage()
    {
        if (ctlImage.HasFile)
        {
            string imageURL = Helpers.ApplicationPath + "accounts/tvs/ImageBank/" + ctlImage.PostedFile.FileName;
            ctlImage.SaveAs(imageURL);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearFields();
    }
}

所以我的问题是:弹出窗口显示正常,显示从GridView中选择的记录,编辑似乎就可以了。但是,由于某种原因,我对表单字段所做的更改不会。当我运行调试器并输入断点来检查表单字段中的值时,它们仍然是原始值,而不是新值。我不明白! 我使用相同的表单将新记录添加到数据库中(单击SingleCards.aspx页面上的“添加新卡”链接,它就可以了)并且可以添加。只是不更新​​。 我真的可以帮助理解这一点。

第二个问题...在SingleCards.aspx页面中,您会看到一个名为“btnRefresh”的按钮,它自然会重新加载GridView控件。作为页面的JQuery代码中的模态窗口关闭代码的一部分,应该调用该按钮的“Click”事件以在用户关闭模态窗口时刷新gridview,但事实并非如此。任何指针为什么? 万分感谢大家!

2 个答案:

答案 0 :(得分:0)

彻底了解行为后,我正在修改我的答案:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ClearFields();
            LoadCardInfo();

        }
    }

在回发后执行的第一件事是Page_Load事件,在这种情况下重新加载旧的表单值。将LoadCardInfo()移至(!Page.IsPostBack)应该会消除所描述的行为。

另外刷新不起作用 尝试: ....

close: function Refresh() {
var RefreshButton = $('<%= btnRefresh.ClientID %>');
RefreshButton.click();
}

..并尝试逐步执行该代码,或者设置一些alert()来查看事件是否被触发

答案 1 :(得分:0)

我会考虑以不同的方式写这篇文章。我也尝试过非常相似的东西。完整的回发,启动脚本和对话框的挫折 - 它永远不会结束。另一种方法:

将数据绑定到网格视图。 在GridView的RowDataBound事件中(在CS端)添加onclick事件处理程序。传递您尝试更新的记录的ID。 在JS方面,当触发此处理程序时,弹出一个JQ模式对话框。 使用BlockUI阻止模式对话框。 使用页面方法/ Web服务获取数据 检索数据时,取消阻止对话框。 在对话框上单击按钮时更新数据库和网格。刷新网格可能很棘手,因为记录的顺序可能会改变 - 我写了一个web服务来替换表中的一行,我手动完成。

这样运行得更快,并且似乎几乎是瞬间运行,因为对话框几乎立即出现。最重要的是,您不必处理CS方面的“事件”,更新面板等。这意味着您必须亲自动手使用JS。最后,它会表现得更好,并且不会有任何“黑匣子”发生的事情,你没有任何可见性。