Codebhind javascript警告YES和NO无法正常工作

时间:2015-11-02 10:39:12

标签: javascript asp.net

我已经写了YES和NO的确认消息。 这是代码: -

 function myTestFunction() {
         if (confirm('Are you sure you want to override the file ?')) {
             return true;
         }
         else {
             return false;
         }
     }

另见背后的代码: -

 if (DtMain.Rows.Count > 0)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
    }

现在我的问题是,当我点击“否”时,它仍然向前移动并且数据被保存。这里出了什么问题

更新代码

protected void btnSave_Click(object sender, EventArgs e)
{

    DataTable dtExcel = new DataTable();
    dtExcel.Clear();
    string StrCount = String.Empty;
    string connString = "";
    HttpPostedFile File = FileUpload1.PostedFile;
    string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
    string path = FileUpload1.PostedFile.FileName;
    string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
    path = Server.MapPath(@"~/Excels/" + "/" + Filename.ToString());

    File.SaveAs(path);
    if (strFileType.Trim() == ".xls")
    {
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
    }
    else if (strFileType.Trim() == ".xlsx")
    {
        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
    }
    string query = "SELECT * FROM [Sheet 1$]";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Close();
    if (conn.State == ConnectionState.Closed)
        conn.Open();
    OleDbCommand cmd = new OleDbCommand(query, conn);
    OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);

    daExcel.Fill(dtExcel);
    conn.Close();

    DataTable DtMain = CF.ExecuteDT("select Tran_type, Order_Date, Region_Mkey from WMS_Future_Del_Order_Hdr where Tran_type = '" + CmbTypeOfAsn.SelectedValue + "' and Order_Date = convert(datetime,'" + TxtEdate.Value + "',103) and Region_Mkey = '" + ddlRegion.SelectedValue + "'");

    if (DtMain.Rows.Count > 0)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
    }

    StringBuilder StrPubBldg = new System.Text.StringBuilder();
    XmlWriter xw = XmlWriter.Create(StrPubBldg);

    string ExcelfileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

    xw.WriteStartElement("DocumentElement");
    {
        xw.WriteStartElement("WMS_Future_Del_Order_Hdr");
        xw.WriteElementString("Comp_mkey", "0");
        xw.WriteElementString("FDepartment_ID", "W");
        xw.WriteElementString("FModule_id", "W");
        xw.WriteElementString("Tran_type", CmbTypeOfAsn.SelectedValue);
        xw.WriteElementString("Doc_no", "1");
        xw.WriteElementString("Doc_date", System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
        xw.WriteElementString("Order_Date", TxtEdate.Value);
        xw.WriteElementString("Import_Filename", Filename);
        xw.WriteElementString("Save_File_Name_Path", Server.MapPath("~/FutureDelivery/") + ExcelfileName + ".xls");
        xw.WriteElementString("Note_Remarks", txtRemarks.Text);
        xw.WriteElementString("User_id", "1");
        xw.WriteElementString("U_DateTime", System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
        xw.WriteElementString("Delete_flag", "N");
        xw.WriteEndElement();

        string STRLine_Id = "0";
        string STRItem_Mkey = "1";
        string STRItem_Code = "2";
        string STRItem_Desc = "3";
        string STRLot_Batch_No = "4";
        string STRExp_Dt = "";
        string STRBx_Bg = "6";
        string STRNet_Wgt = "7";
        string STRQty = "8";
        string STRNo_of_Pallets = "9";
        DataTable ParaDt = CF.ExecuteDT("select * from WMS_Mapping_Para_Table");
        for (int i = 0; i < ParaDt.Rows.Count; i++)
        {
            if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Line_Id")
            {
                STRLine_Id = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Item_Mkey")
            {
                STRItem_Mkey = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Item_Code")
            {
                STRItem_Code = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Item_Desc")
            {
                STRItem_Desc = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Lot_Batch_No")
            {
                STRLot_Batch_No = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Exp_Dt")
            {
                STRExp_Dt = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Qty")
            {
                STRQty = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Bx_Bg")
            {
                STRBx_Bg = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }
            else if (ParaDt.Rows[i]["Txn_Column_Name"].ToString() == "Net_Wgt")
            {
                STRNet_Wgt = ParaDt.Rows[i]["Sheet_Int_Id"].ToString();
            }

        }
        if (dtExcel.Rows.Count > 0)
        {
            for (int i = 0; i < dtExcel.Rows.Count; i++)
            {
                xw.WriteStartElement("WMS_Future_Del_Order_Trl");
                xw.WriteElementString("Sr_No", (i + 1).ToString());
                xw.WriteElementString("Line_Id", dtExcel.Rows[i][Convert.ToInt32(STRLine_Id)].ToString());
                xw.WriteElementString("Item_Mkey", dtExcel.Rows[i][Convert.ToInt32(STRItem_Mkey)].ToString());
                xw.WriteElementString("Item_Code", dtExcel.Rows[i][Convert.ToInt32(STRItem_Code)].ToString());
                xw.WriteElementString("Item_Desc", dtExcel.Rows[i][Convert.ToInt32(STRItem_Desc)].ToString());
                xw.WriteElementString("Lot_Batch_No", dtExcel.Rows[i][Convert.ToInt32(STRLot_Batch_No)].ToString());
                xw.WriteElementString("Exp_Dt", Convert.ToDateTime(dtExcel.Rows[i][Convert.ToInt32(STRExp_Dt)].ToString()).ToShortDateString());
                xw.WriteElementString("Qty", dtExcel.Rows[i][Convert.ToInt32(STRQty)].ToString());
                xw.WriteElementString("Bx_Bg", dtExcel.Rows[i][Convert.ToInt32(STRBx_Bg)].ToString());
                xw.WriteElementString("Net_Wgt", dtExcel.Rows[i][Convert.ToInt32(STRNet_Wgt)].ToString());
                xw.WriteElementString("No_of_Pallets", dtExcel.Rows[i][Convert.ToInt32(STRNo_of_Pallets)].ToString());
                xw.WriteElementString("Creation_Date", System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                xw.WriteElementString("Update_Date", System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                xw.WriteElementString("Created_By", "1");
                xw.WriteElementString("Updated_By", "1");
                xw.WriteElementString("User_id", "1");
                xw.WriteElementString("U_DateTime", System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                xw.WriteEndElement();
            }
        }
        xw.Close();
        String strretmkey = InsertUpdateDelete.InsertUpdateDeleteCls.InsertUpdateDelete_sql(Hid_Mode.Value, Convert.ToInt32(Hid_MKey.Value), "WMS_Future_Del_Order_Hdr", "MKEY", "FD", StrPubBldg.ToString());
        DataTable dt = CF.ExecuteDT("Select Tran_type,DATEPART(yyyy,U_DateTime) AS U_DateTime,DATEPART(mm,U_DateTime) AS U_DateTime from WMS_Future_Del_Order_Hdr where mkey ='" + strretmkey + "'");
        StrDocNo = strretmkey + '/' + dt.Rows[0][0].ToString() + '/' + dt.Rows[0][2].ToString() + dt.Rows[0][1].ToString();

        ExcelfileName = StrDocNo.ToString().Replace("/", "_");
        string strPathval = Server.MapPath("~/FutureDelivery/") + ExcelfileName + ".xls";
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FutureDelivery/") + ExcelfileName + ".xls");

        CF.ExecuteQuerry("update WMS_Future_Del_Order_Hdr set Doc_no ='" + StrDocNo + "', Save_File_Name_Path ='" + strPathval + "' where mkey=" + strretmkey + "");

        lblDocNo.Text = StrDocNo.ToString();
        Hid_MKey.Value = strretmkey;
    }

    ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "alert('Record saved successfully.');", true);
    FunGridBind();

    btnSave.Enabled = false;
}

2 个答案:

答案 0 :(得分:1)

因为您不能以这种方式将服务器端代码执行与客户端代码混合。因此,根据讨论,可以使用以下两种方法来实现。

方法1:使用CheckBox

在您的aspx /前端放置一个CheckBox,例如

<asp:CheckBox ID="chkOverwriteFile" runat="server" Text="Overwrite existing file" />

然后在btnSave.Click事件的代码后面使用它,如下所示

protected void btnSave_Click(object sender, EventArgs e)
{
    //////////////////// YOUR OTHER CODE

    DataTable DtMain = CF.ExecuteDT("select Tran_type, Order_Date, Region_Mkey from WMS_Future_Del_Order_Hdr where Tran_type = '" + CmbTypeOfAsn.SelectedValue + "' and Order_Date = convert(datetime,'" + TxtEdate.Value + "',103) and Region_Mkey = '" + ddlRegion.SelectedValue + "'");

    bool blWriteReecord = false;
    if (DtMain.Rows.Count > 0)
    {
        if (chkOverwriteFile.Checked) {
            blWriteReecord = true;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "alert('Record already exitst. If you want to overwrite it then select Overwrite existing file and then save again.');", true);
        }
    }
    else
    {
        blWriteReecord = true;
    }

    if (blWriteReecord) {
        StringBuilder StrPubBldg = new System.Text.StringBuilder();

        ///////////////// YOUR OTHER CODE

        FunGridBind();

        btnSave.Enabled = false;
    }
}

代码块将检查已存在的文件/记录。如果它存在,那么它将要求用户选择CheckBox来覆盖记录。

然后用户选中该复选框并再次提交。它只是选择是/否确认消息框作为选择复选框的替代方法。

此外,如果您想扩展它,那么您最初可以隐藏复选框,并仅在记录存在时显示。

方法2:使用隐藏的div

在这种方法中,您可以按照以下步骤操作:

  1. 与您的FileUploadbtnSave一起,您在前端包含一个隐藏的消息div,其设计类似于包含您的消息的MessageBox和Yes的两个按钮(btnYes,服务器端为如果你想使用AJAX和No,则调用代码隐藏或客户端。 (此消息div可以是基于CSS / JavaScript或根据您的方便或框架)
  2. btnSave.Click上检查文件/记录,如果不存在,通常会保存。如果它确实存在,那么你从提示覆盖或不覆盖的代码中调用隐藏的div。
  3. 如果用户选择No,只需隐藏消息div并不执行任何操作。
  4. 如果用户选择Yes调用与btnSave.Click中相同的代码但不提示用户输入现有文件/记录,则只需覆盖它。
  5. 为了避免重复,可以将代码重新组织成子部分,即可以从消息div的btnSave.ClickYes按钮调用的函数/ subs,并使用附加参数来决定是否覆盖文件或显示消息div。

答案 1 :(得分:0)

您的函数的返回值没有任何变化,只有在您的页面加载后才会调用它,这就是它。你应该用它做点什么。

此外,似乎已在执行操作时向用户显示该问题。

因此,您应该转到HTML页面,其中包含您正在提交的表单(或类似操作),以触发操作。在那里你应该放这样的东西:

<form onsubmit="return confirm('Are you sure you want to override the file ?')"
      action=... >

另请注意,您的功能不必要很长。它将true翻译为true,将false翻译为false。您只需返回confirm的值即可。 onsubmit属性可用于验证表单,如果其值为false,则不会提交表单;用户留在页面上。