c# - 表单提交后清除(重置)表单字段(数据)

标签 c# asp.net sql-server

我如何在提交表单后清除(重置)表单域

 protected void lb_insert_Click(object sender, EventArgs e)
    {
        try
        {

            FormView _f = FormView1;
            usercredential uc = UserHandler.GetUserCredential(UserHandler.GetUserNameAD());
            int id_spv = int.Parse(uc.usrID); int? code_section = int.Parse(uc.usrSectionId);
            if (((CheckBox)_f.Controls[0].FindControl("other_spv")).Checked)
            {
                id_spv = int.Parse(((HiddenField)_f.Controls[0].FindControl("hid_other_spv_id")).Value);
                code_section = int.Parse(dbcontext.tbl_ref_UserHzr
                                                    .Where(p => p.code_hzrUser == id_spv)
                                                    .Select(r => r.code_section)
                                                    .First().ToString());
                //code_section = dbcontext.tbl_ref_UserHzr.Where(x => x.code_hzrUser == id_spv).Select(x => x.code_section).SingleOrDefault();
            }

            #region <insert new hazard report to tbl_hzr_main />
            tbl_hzr_main newitem = new tbl_hzr_main();
            newitem.code_company = int.Parse(((CustomControls_DdlCompany)_f.Controls[0].FindControl("ddl_company1")).SelectedValue);
            newitem.code_empPIC = int.Parse(((HiddenField)_f.Controls[0].FindControl("hid_pic_id")).Value);
            newitem.code_hzrUser = id_spv;
            newitem.code_incdLocation = int.Parse(((CustomControls_DdlLocation)_f.Controls[0].FindControl("ddl_location1")).SelectedValue);
            newitem.code_main_contractor = int.Parse(((CustomControls_DdlCompany)_f.Controls[0].FindControl("ddl_company1")).SelectedMainConValue);
            newitem.code_section = code_section;
            newitem.code_usrEntry = int.Parse(uc.usrID);
            newitem.date_hzrMain = DateTime.Parse(((TextBox)_f.Controls[0].FindControl("TextBox1")).Text);
            newitem.desc_hzrMain = ((TextBox)_f.Controls[0].FindControl("TextBox3")).Text;
            newitem.dueDate_hzrMain = DateTime.Parse(((TextBox)_f.Controls[0].FindControl("TextBox1")).Text);
            newitem.entryDate_hzrMain = DateTime.Now;
            newitem.folup_hzrMain = ((TextBox)_f.Controls[0].FindControl("TextBox4")).Text;
            newitem.locDetail_hzrMain = ((TextBox)_f.Controls[0].FindControl("txb_loc_detail")).Text;
            newitem.PICsign_status = byte.Parse(((RadioButtonList)_f.Controls[0].FindControl("rbl_sign_pic")).SelectedValue);
            newitem.stat_hzrMain = byte.Parse(((RadioButtonList)_f.Controls[0].FindControl("RadioButtonList1")).SelectedValue);

            dbcontext.tbl_hzr_main.Add(newitem);
            dbcontext.SaveChanges();
            #endregion

            #region <get latest hazard report ID for foreign key />
            long id_hazard_report = long.Parse(dbcontext.tbl_hzr_main
                                                .OrderByDescending(o => o.code_hzrMain)
                                                .Select(s => s.code_hzrMain)
                                                .First().ToString());
            //long id_hazard_report = dbcontext.tbl_hzr_main.OrderByDescending(p => p.code_hzrMain).Select(x => x.code_hzrMain).SingleOrDefault();
            #endregion

            #region <insert finding type/criteria />
            tbl_hzrCriteria newcrititem = new tbl_hzrCriteria();

            //RadioButtonList rbl_crit = (RadioButtonList)_f.Controls[0].FindControl("rbl_finding_type");
            //foreach (ListItem rb in rbl_crit.Items)
            //{
            //    if (rb.Selected)
            //    {
            //        newcrititem.code_hzrCritItem = int.Parse(rb.Value);
            //    }
            //}
            newcrititem.code_hzrCritItem = int.Parse(((RadioButtonList)_f.Controls[0].FindControl("rbl_finding_type")).SelectedValue);
            newcrititem.code_hzrMain = id_hazard_report;
            dbcontext.tbl_hzrCriteria.Add(newcrititem);
            dbcontext.SaveChanges();
            #endregion

            #region <insert risk level if location kelanis />
            if (((CustomControls_DdlLocation)_f.Controls[0].FindControl("ddl_location1")).SelectedText.ToLower().Trim() == "kelanis")
            {
                TBL_HZR_MAIN_RISKLEVEL newriskitem = new TBL_HZR_MAIN_RISKLEVEL();
                newriskitem.code_hzrMain = id_hazard_report;
                newriskitem.code_risk_level = int.Parse(((CustomControls_DdlRiskLevel)_f.Controls[0].FindControl("ddl_risklvl1")).SelectedValue);
                dbcontext.TBL_HZR_MAIN_RISKLEVEL.Add(newriskitem);
            }
            #endregion

            #region <upload file(s) and insert name to database />
            // Get the HttpFileCollection
            //if(Page.IsValid)
            //  {
            //      //your logic
            //  }

            HttpFileCollection hfc = Request.Files;
            if (hfc != null)
            {
                string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);

                string PicDir;
                if (Directory.Exists(cekDir)) //check Folder avlalible or not
                {
                    PicDir = cekDir;
                }
                else
                {
                    DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
                    PicDir = cekDir;
                }

                string fullname;
                string filename;            
                //FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
               // string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension 


                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string fileExt = Path.GetExtension(hpf.FileName);

                    if (hpf.ContentLength >0) 
                    {
                        ///full path name to check exist or not
                        fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
                        bool ex = File.Exists(fullname);
                        if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
                        {
                            if(hpf.ContentLength > 200000)/*(hpf.ContentLength > 200000)*/
                            {

                                ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
                                continue;
                            }


                            if (ex == true)
                            {

                                string f = Path.GetFileName(hpf.FileName.Replace(" ", "_"));
                                string[] a = new string[1];
                                a = f.Split('.');
                                filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
                            }

                            else
                            {
                                filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();

                            }

                        ///full path name to store in database with new filename
                        //string[] aa = new string[1];
                        //filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
                        fullname = string.Format("{0}\\{1}", PicDir, filename);
                        hpf.SaveAs(fullname);
                        InsertHazardDoc(id_hazard_report, filename);
                        }
                        else
                        {
                           // FileUpload1.Focus();
                            ClientScript.RegisterStartupScript(Type.GetType("System.String"),"messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
                            continue;
                        }
                    }
                 //}

                }
            }
            #endregion

            //Page.DataBind();

            myfb._success("Hazard Report Succesfully Inserted");
//after show notification above I want to clear data or reset


        }
        catch (Exception ex)
        {

            myfb._error(ex.ToString());
        }

    }

通知后我在哪里写重置代码myfb._success("Hazard Report Succesfully Inserted");

最佳答案

您可以使用 Response.Redirect(Request.RawUrl) 重新加载当前页面;

这将执行完整的回发并从头开始重新加载页面。如果您没有设置任何自定义代码,将您的值存储在某种缓存或 session 存储中,您的表单应该会恢复干净。

//更新:

如果您想显示某种成功消息,您可以将查询字符串附加到您的重定向。在我的示例中,我有一个文本框,它显示“它有效”和一个提交按钮,它执行重定向:

protected void Page_Load(object sender, EventArgs e)
{
    if(Request.QueryString["success"] == "true")
    {
        //show success here
        txtSuccess.Visible = true;
    }
    else
    {
        //set success invisible
        txtSuccess.Visible = false;
    }
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    var url = Request.RawUrl;
    //check if querystring already present
    if (url.IndexOf('?') == -1) {
        //create a querystring
        Response.Redirect($"{url}?success=true");
    }
    else
    {
        //append to existing querystring parameters
        Response.Redirect($"{url}&success=true");
    }

}

这是做什么的,它将一个成功的查询字符串参数附加到您的 url。它确实通过检查 url 中的 ? 字符来检查查询字符串是否已经存在。

然后它构建 url 并重定向。在您的 Page_Load 方法中,您只需检查该查询字符串。如果存在,则显示成功消息,如果不存在,则将其隐藏。

非常简单,但它完成了它的工作。

关于c# - 表单提交后清除(重置)表单字段(数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157897/

相关文章:

c# - 如何将 xml 导出到数据库 - asp.net

mysql - SQL Server 2008 的 ADDTIME 和 SEC_TO_TIME

sql - 如何解决这个 SQL 查询(标题和详细信息)?

c# - 如何将 XML 读入与其 xsd 匹配的类中

c# - ASP.NET 按日期范围对多个 SQL 数据库表进行排序

移动设备上的 Javascript window.close

javascript - js 和 css 版本控制

c# - WindowsIdentity.GetCurrent().Name 获取应用程序池名称而不是用户名

c# - 从对 LyncClient.GetClient() 的调用中获取无效对象

asp.net - “检测到 Autofac 循环组件依赖性”错误