当C#验证失败时,停止运行JavaScript代码

时间:2017-05-16 13:19:49

标签: javascript c# sql-server

我试图阻止JavaScript代码在表格中找到数据时运行(dt.Rows.Count > 0)。目前代码没有在数据库中插入数据(我想要的),但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 MBID=@MBID ", 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();
}

1 个答案:

答案 0 :(得分:1)

XMLHttpRequest有一个事件监听器onreadystatechange,在http请求正在进行时调用。当readyState为4时,请求已完成。此时,您可以拦截从函数返回的内容,并确定应显示哪个警报。

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