aj.net回发后的Asp.net gridview itemtemplate复选框列处于不正确的状态(C#)

时间:2012-07-02 02:32:29

标签: c# asp.net ajax gridview postback

我在尝试将复选框itemtemplate字段集成到ASP.net gridview时遇到问题。具体来说,我在异步回发后处理用户修改的复选框状态时遇到问题(可能是由于我的数据绑定方式)。

请注意,我必须使用异步回发,因为页面内容会动态引入HTML <div>

在渲染的字段中有两个应允许用户修改SQL数据库字段:IsPrimaryIsEnabled(显示为IsActive)。

我成功呈现了这些字段的状态:当IsPrimary在数据库中等于'N'时,取消选中该复选框,当它等于'Y'时,复选框被选中。

这一切都很棒。但是,我希望允许用户更改复选框的选中状态,以便在异步回发后将相应的数据库字段从“Y”切换为“N”。

我想要做的是:当用户切换复选框的状态(绑定到数据库表)然后提交表单时,服务器端代码应该进行适当的数据库更改。

我的问题是,当我尝试在异步回发之后从代码隐藏中访问字段时,它们似乎未被用户修改。也就是说,它们出现在数据库中,而不是在用户修改后出现。

据我所知,这与我将数据绑定到gridview的方式有关。

不幸的是,我手动绑定数据没有成功。

以下是相关的客户代码:

   <asp:objectdatasource id="ObjectDataSource2" runat="server" dataobjecttypename="MPads.DataAccess.PatientInsuranceCard"
    deletemethod="DeletePatientInsuranceCard" insertmethod="SavePatientInsuranceCard"
    selectmethod="ListPatientInsuranceCardsByPatientId" typename="MPads.DataAccess.Repositories.PatientCardRepository"
    updatemethod="SavePatientInsuranceCard">
    <selectparameters>
        <asp:sessionparameter dbtype="Guid" name="patientId" sessionfield="patientId" />
    </selectparameters>
</asp:objectdatasource>
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" backcolor="White"
    bordercolor="White" borderstyle="Ridge" borderwidth="2px" cellpadding="0" 
    gridlines="None" style="margin-right: 0px" width="695px" datakeynames="PatientInsuranceCardId"
    clientidmode="Predictable" viewstatemode="Enabled" datasourceid="ObjectDataSource2">
    <columns>
        <asp:boundfield datafield="PatientInsuranceCardId" headertext="PatientInsuranceCardId" sortexpression="PatientInsuranceCardId" visible="False"/>
        <asp:boundfield datafield="Company" headertext="Company" sortexpression="Company" />
        <asp:boundfield datafield="MemberId" headertext="Member ID" sortexpression="MemberId" />
        <asp:boundfield datafield="GroupNumber" headertext="Group ID" sortexpression="GroupNumber" />
        <asp:boundfield datafield="SubscriberId" headertext="Subscriber ID" sortexpression="SubscriberId" />
        <asp:boundfield datafield="DateLastModified" headertext="Last Modified" sortexpression="DateLastModified"  />
        <asp:templatefield headertext="Primary" sortexpression="IsPrimary">
            <itemtemplate>
                <asp:checkbox id="chkIsPrimary" runat="server" checked='<%# bool.Parse(Eval("IsPrimary").ToString() == "Y" ? "True": "False") %>'
                    enabled="true " />
            </itemtemplate>
        </asp:templatefield>
        <asp:templatefield headertext="Active" sortexpression="IsActive">
            <itemtemplate>
                <asp:checkbox id="chkIsActive" runat="server" checked='<%# bool.Parse(Eval("IsEnabled").ToString() == "Y" ? "True": "False") %>'
                    enabled="true " />
            </itemtemplate>
        </asp:templatefield>

以下是“提交”表单的客户端代码:

function loadAjaxContent(pageName, postType, arrayData) {
  <div id="pageContent_3" class="content">
        <div class="wrap2" style="clear: both; margin-top: 50px;">
            <div class="style9" style="clear: both; padding-right: 0px; padding-left: 0px; margin-top: 0px;">
                <input id="btnAddMore" type="button" value="Submit insurance" onclick="if(PageValidate()){ loadAjaxContent('InsuranceInformation','POST') };" />
                <input id="btnSkip" type="button" value="I don't have insurance (skip)" onclick="loadAjaxContent('EmergencyContacts','POST',null)" />
                <input type="hidden" id="isPCP" name="isPCP" value="0" runat="server" />
            </div>
        </div>
    </div>
    // Check for post type
    if (typeof postType == "undefined")
        postType = "GET";

    // If no data is passed -- serialize all input,select,textarea fields
    // do not pass the viewstate -- will cause errors
    if (typeof arrayData == "undefined")
        arrayData = $(":input:not(#__VIEWSTATE)").serializeArray();

    var targetPage = "../Ajax/" + pageName + ".aspx";

    // Show loading badge
    $content.hide();
    $loading.show();

    var ajaxRequest = $.ajax({
        url: targetPage,
        type: postType,
        data: arrayData,
        complete: function(result, status) {
            var response = $.trim(result.responseText);

            // Disable input fields before request is made
            $('input').removeAttr('disabled');

            // Show appropriate results
            if (status == "success") {
                $content.html(response);

                var hidingOptions = { times: 2 };
                var hidingCallback = function() {
                    $content.show();

                    if ($(".ContentPage:visible").length > 0) {
                        $(".ContentPage:visible > .inputfield").first().click();
                    } else {
                        $(".inputfield").first().click();
                    }
                };

                $loading.hide("pulsate", hidingOptions, 200, hidingCallback);
            }

            if (document.getElementsByTagName("input").length === 0) {
                $(":input").removeAttr("disabled");
            }
            ;
        },
        error: function() {
            $content.load("Ajax/PageNotFound.aspx", function() {
                $content.show();
                $loading.hide();

                $(":input").removeAttr("disabled");
            });
        }
    });
}

;
enter code here

以下是最不相关且无功能的服务器端代码:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using MPads.Common;
using MPads.WebPatientPortal.Interfaces;
using MPads.WebPatientPortal.Presenters;


namespace MPads.WebPatientPortal.Ajax
{
    public partial class InsuranceInformation : Page, IInsuranceInformation
    {
        private InsuranceInformationPresenter _presenter;


        protected void Page_Init(object sender, EventArgs e)
        {

            var dataKeys = new ArrayList();
            var dataIsPrimary = new ArrayList();
            var dataIsActive = new ArrayList();


            foreach (GridViewRow row in GridView1.Rows)
            {
                dataKeys.Add(GridView1.DataKeys[row.DataItemIndex].Value);
                dataIsPrimary.Add(((CheckBox)row.FindControl("chkIsPrimary")).Checked);
                dataIsActive.Add(((CheckBox)row.FindControl("chkIsActive")).Checked);

                System.Diagnostics.Trace.WriteLine("Page_init : Gridview1.rows = " + GridView1.Rows.Count);
            }


        }

        protected void Page_Load(object sender, EventArgs e)
        {

            var fields = Request.Form;



            System.Diagnostics.Trace.WriteLine("fields = "+fields);


            _presenter = new InsuranceInformationPresenter();
            _presenter.Init(this);
            // Get userId
            if (fields.Count > 0)
            {

                System.Diagnostics.Trace.WriteLine("Gridview1.rows = " + GridView1.Rows.Count);

                var insuranceName = Utilities.GetNvpValue(fields, "txtInsuranceName");
                var planName = Utilities.GetNvpValue(fields, "txtPlanName");
                var groupId = Utilities.GetNvpValue(fields, "txtGroupId");
                var memberId = Utilities.GetNvpValue(fields, "txtMemberId");
                var copayO = Utilities.GetNvpValue(fields, "txtCopayO");
                var copayS = Utilities.GetNvpValue(fields, "txtCopayS");
                var copayE = Utilities.GetNvpValue(fields, "txtCopayE");

                var deductible = Utilities.GetNvpValue(fields, "txtDeductible");
                var coinsurance = Utilities.GetNvpValue(fields, "txtCoinsurance");
                var memberSince = Utilities.GetNvpValue(fields, "txtMemberSince");
                var isPrimary = Utilities.GetNvpValue(fields, "btnInsuranceType");


                var dataKeys      = new ArrayList();
                var dataIsPrimary = new ArrayList();
                var dataIsActive  = new ArrayList();


                foreach (GridViewRow row in GridView1.Rows)
                {
                    dataKeys.Add(GridView1.DataKeys[row.DataItemIndex].Value);
                    dataIsPrimary.Add(((CheckBox) row.FindControl("chkIsPrimary")).Checked);
                    dataIsActive.Add(((CheckBox) row.FindControl("chkIsActive")).Checked);
                }

                _presenter.UpdatePatientInsuranceCard(dataKeys, dataIsPrimary, dataIsActive);



                _presenter.SavePatientInsuranceA(insuranceName, planName, groupId, memberId,
                    copayO, copayS, copayE, deductible, coinsurance, memberSince, isPrimary);

                //
            }
        }

        public int GetPageNum()
        {
            return (1);
        }

        public void DisplayErrorMessage(string message)
        {
            //errorMessageContainer.Visible = true;
            // errorMessageContainer.InnerText = message;
        }

        public void loadAjaxContent(string content)
        {
            Page.RegisterStartupScript("myScript", " <script type=\"text/javascript\"> loadAjaxContent(" + content + ",'POST',null); </script>");
        }

        public void SetInsuranceLabel(string text)
        {
        }


    }
}

我对此有点过头了,我会为这个问题找到一个简明实用的答案。我已经考虑过使用javascript获取复选框字段,然后在DataKey事件期间使用相应的onchecked填充隐藏的文本框,但我没有完成此任务的知识(特别是因为ID被错误asp.net)。请帮忙:) :(

0 个答案:

没有答案