2017-05-16 79 views
0

我試圖停止在表中找到數據時運行的JavaScript代碼(dt.Rows.Count > 0)。目前代碼沒有在數據庫中插入數據(我想要的),但JavaScript繼續運行,因爲我仍然獲得了成功的插入消息。謝謝!當C#驗證失敗時停止運行JavaScript代碼

HTML

<input type="button" id="btnAddConsent" value="Add Consent" onclick="insertData();" /> 

的JavaScript

function insertData() { 
    var MBID = document.getElementById("txtConsentMBID").value; 
    var ConsentID = document.getElementById("DropDownListConsent").value; 
    var ConsentDate = document.getElementById("txtPatientConsentDate").value; 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.open("GET", "insertConsent.aspx?mb=" + MBID + " &ci= " + ConsentID + "&cd=" + ConsentDate, false); 
    xmlhttp.send(null); 

    ConsentID = document.getElementById("DropDownListConsent").value = ""; 
    ConsentDate = document.getElementById("txtPatientConsentDate").value = ""; 
    alert("Consent Added Successfully"); 
} 

C#

using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString)) 
{ 
    MBID = Request.QueryString["mb"].ToString(); 
    ConsentID = Request.QueryString["ci"].ToString(); 
    ConsentDate = Request.QueryString["cd"].ToString(); 

    con.Open(); 

    using (SqlCommand sc = new SqlCommand(@" select * from ConsentGroup where ConsentID = @ConsentID and [email protected] ", con)) 
    { 
     sc.Parameters.AddWithValue("@MBID", MBID); 
     sc.Parameters.AddWithValue("@ConsentID", ConsentID); 
     //sc.Parameters.AddWithValue("@ConsentDate", ConsentDate); 
     //sc.ExecuteNonQuery(); 

     DataTable dt = new DataTable(); 
     SqlDataAdapter da = new SqlDataAdapter(sc); 
     da.Fill(dt); 
     if (dt.Rows.Count > 0) 
     { 
      // this message should displayed when count is more that 1 
      Response.Write("alert('This Patient already has this Concent saved in the Database');"); 
     } 
     else 
     { 
      using (SqlCommand sc1 = new SqlCommand(@"insert into ConsentGroup (MBID, ConsentID, ConsentDate, ConsentWithdraw, ConsentConfirm) 

      values('" + MBID + "','" + ConsentID + "','" + ConsentDate + "','NO','YES')", con)) 
      { 
       sc1.ExecuteNonQuery(); 
      } 
     } 
    } 

    con.Close(); 
} 
+3

確認...你參數化了你的第一個查詢,但是你的insert語句對sql注入是開放的。你爲什麼改變?您需要參數化所有查詢。你可以看看這個。 http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ –

回答

1

XMLHttpRequest有一個事件監聽器onreadystatechange當http請求正在進行時被調用。當readyState爲4時,請求完成。此時,您可以攔截從您的函數返回的內容,並確定應顯示哪個警報。

xmlhttp.onreadystatechange = function() 
{ 
    if (request.readyState == 4 && request.status == 200) 
    { 
     alert(request.responseText); 
    } 
} 
+0

感謝您的幫助 –