2017-07-18 46 views
1

我如何清除(重置)形式後形式的Fileds提交復位(復位)表單域(數據)提交

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");

+0

創建一個新的形式,處置舊的? – artm

+0

是創建一個新表單處理舊數據,畢竟數據提交和通知myfb._success(「危險報告成功插入」); – Rahmat

+0

就像「Response.Redirect(Request.Url.AbsoluteUri)」,但如果使用我的通知不顯示,可以幫我嗎? – Rahmat

回答

0

我的理解你想重置所有字段,然後顯示通知。然後

protected void lb_insert_Click(object sender, EventArgs e){ 
    //your previous code... 

    Session["State"] = "success"; 
    Response.Redirect(Request.RawUrl); 

} 

在page_init: 你可以試試這個

protected void Page_Load(object sender, EventArgs e){ 
    string state= (string)Session["state"]; 
    if(!string.isNullOrEmpty(state)){ 
     //show your notification here 
    } 

    Session.remove("state"); 
} 
+0

這是我想要的。優秀 – Rahmat

0

你可以試試對此,

FormId.Datasource=null; 
FormId.databind(); 
+0

差不多完成我試試這個,但如果從dropdownlist創建新的爲空 – Rahmat

1

您只需重新加載當前網頁與Response.Redirect(Request.RawUrl);

這將執行完整的回發並從頭開始重新加載頁面。如果您尚未設置任何自定義代碼,將您的值存儲在某種緩存或會話存儲中,則您的表單應該恢復爲乾淨。

//更新:

如果你想顯示某種成功的消息,你可以追加一個查詢字符串到您的重定向。在我的例子我有一個文本框,顯示「它的工作」和一個提交按鈕,這並不重定向:

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中的?字符來檢查查詢字符串是否已經存在。

然後它建立網址並重定向。在你Page_Load方法你然後只是檢查查詢字符串。如果它在那裏,你會顯示你的成功信息,如果沒有 - 你會隱藏它。

真的很簡單,但它的工作。

+0

我嘗試「Response.Redirect( Request.RawUrl);」是工作但沒有通知顯示「myfb._success(」危險報告成功插入「);」 – Rahmat

+0

如果我上傳文件只有圖像和filesize沒有通知後添加'Response.Redirect(Request.RawUrl);'可以幫我 ? – Rahmat

+0

這聽起來像是一個不同的問題。請在SO上提出一個新問題。 – Marco