gpt4 book ai didi

javascript - 在没有页面刷新的情况下直接从 javascript 调用没有按钮单击的 asp.net 函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:57 25 4
gpt4 key购买 nike

我正在尝试检查数据库中是否存在运行完美的特定值,但我想要的是

  1. 我想从 JavaScript 调用 C# 函数
  2. 就像现在在我的代码中一样,在 JavaScript 单击按钮后它会响应,但是页面也会刷新 我不希望发生页面刷新
  3. 在不使用 javascript 按钮的情况下调用 C# 函数的更好方法

    protected void Check_exam_id(object sender, EventArgs e)
    {
    string DDSelected_Class = DD_class.SelectedValue;// store it in some variable;
    string DD__Method = DD_Method.SelectedValue;// store it in some variable;

    if (DD__Method == "THEORY")

    {
    using (MySqlConnection myConnection = new MySqlConnection(constr))
    {
    string oString = "Select * from score_master WHERE Class=@DDSelected_Class ";
    MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
    oCmd.Parameters.AddWithValue("@DDSelected_Class", DDSelected_Class);

    myConnection.Open();
    using (MySqlDataReader oReader = oCmd.ExecuteReader())
    {

    if (oReader == null || !oReader.HasRows)
    {
    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);


    }
    else
    {
    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert2", "alert('Exist')", true);

    myConnection.Close();
    }
    }

    }


    }

    }

asp 按钮

 <asp:Button runat="server" id="Check_examid"  AutoPostback = "false" onclick='Check_exam_id'   style="  display:none;   float: right;    width: 22%;    height: 41px;    text-align: center;    background: #EAEAEA;    border: none;    border-color: #EAEAEA;    margin-top: 2%;" Text="Submit"></asp:Button>

Javascript

    document.getElementById("BodyHolder_Check_examid").click()

最佳答案

如评论中所述,您可以使用 jquery ajax 轻松完成。为此,您必须定义一个类似这样的 WebMethod:-

请包括using System.Web.Services;

[WebMethod]
public static bool Check_exam_id(string className, string MethodName)
{
bool examIdExist = false;
if (DD__Method == "THEORY")
{
\\Your logic here
}
\\Based on DB operation return value
examIdExist
}

最后像这样从您的客户端调用它:-

$("#Check_examid").click(function (e) {
e.preventDefault(); //To avoid postback
//Get these values from dropdwon
var className = $("#DD_class").val();
var methodName = $("#DD_Method").val();
var data = { "className": className , "MethodName": methodName };
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Check_exam_id",
data: JSON.stringify(data),
success: function (response) {
if(response.d) //If method returned true.
alert('Exist');
else
alert('No Student Found')
},
error: function (msg) { alert(msg.d); }
});
});

此外,包括 jquery 基础库文件。

关于javascript - 在没有页面刷新的情况下直接从 javascript 调用没有按钮单击的 asp.net 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com