【问题标题】:How to call a backend C# function from front end Javascript function in ASP.NET如何从 ASP.NET 中的前端 Javascript 函数调用后端 C# 函数
【发布时间】:2014-10-03 03:06:38
【问题描述】:

我目前正在 C# 和 Asp.net 进行无薪实习。我的雇主要求我编写一个 javascript 函数,以便告诉用户他们是否确定是否要在删除之前从数据库中删除记录。

经过一些研究,我能够写出 Javascript 函数来告诉用户他们是否确定要在实际从数据库中删除这条记录之前删除它。

javascript 函数有效。但是现在我遇到的问题是如何调用后端 C# 函数,该函数实际上会从我刚刚编写的前端 javascript 函数中删除数据库中的记录?

这是我的代码:

Javascript 函数:

function watchdelete() 
{
    if (confirm("Are you Sure You want to delete this Manufacturer?") == true)
   {
        __doPostBack('btnDelete_Click','');//"PageMethods.btnDelete_Click();
   }
    else { }
}

调用删除按钮附加的javascript客户端代码的前端部分:

<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick=" return watchdelete()" OnClick="btnDelete_Click1" />

我要调用的后端 C# 函数以从数据库中删除记录: (请注意,只要我调用这个函数并执行它,我会很高兴,你不用担心 关于它的内部运作太多了。谢谢)

protected void btnDelete_Click(object sender, EventArgs e)
{
    String com, command, findmodel;

    if (txtManufactureName.Text != "")                                      // If the manufacturer name is not null
    {
        if (txtManufactureName.Text == grdManufact.SelectedRow.Cells[1].Text) // And the manufacturer name must not be
        {                                                                     // Changed from selected one
            string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
            try
            {
                using (SqlConnection conn = new SqlConnection(strConnectionString))
                {
                    conn.Open();                                               // Connect to database
                    String moderated = (checkBoxModerated.Checked) ? "true" : "false";
                    findmodel = "SELECT * From VehicleModels WHERE ManufacturerID = '" + txtManID.Text + "';"; 
                    com = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
                    command = "DELETE From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
                    SqlDataAdapter finder = new SqlDataAdapter(findmodel, conn);
                    DataTable dat = new DataTable();
                    int nummods = finder.Fill(dat);
                    if (nummods == 0)
                    {
                        SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
                        DataTable dt = new DataTable();
                        int number = adpt.Fill(dt);                                // try to find record to delete
                        if (number == 0)                            // If there is no such record to delete
                        {                                           // Indicate this to user with error message
                            txtMessage.Text = "Sorry, there is no such record to delete";
                        }
                        else
                        {                                           // Otherwise delete the record
                            using (SqlCommand sequelCommand = new SqlCommand(command, conn))
                            {
                                sequelCommand.ExecuteNonQuery();
                                txtMessage.Text = "Manufacturer Deleted Successfully";
                                txtManufactureName.Text = "";       // Reset manufacturer name
                                txtDescription.Text = "";           // Reset Description
                                checkBoxModerated.Checked = false;  // clear moderated checkbox
                            }
                        }
                    }
                    else
                    {
                        txtMessage.Text = "Sorry. You must delete associated models first.";
                    }
                    conn.Close();                               // Close the database connection. Disconnect.
                }
                BindGrid();                                     // Bind Manufacturer Grid again to redisplay new status.
            }
            catch (SystemException ex)
            {
                txtMessage.Text = string.Format("An error occurred: {0}", ex.Message);
            }
        }
        else
        {
            txtMessage.Text = "Sorry. You cant change the manufacturer name before deleting";
        }
    }
    else
    {   // Otherwise give error message if manufacturer name missing
        txtMessage.Text = "Please enter a manufacturer name to delete";
    }
}

任何想法都会受到赞赏。

【问题讨论】:

  • 您介意从您的示例中删除不相关的代码并澄清您的问题以与接受的答案保持一致吗? (作为副作用,看起来很痛苦的 SQL 注入将从示例中消失)。还要尽量避免在帖子中使用thank you notes

标签: javascript c# asp.net webforms


【解决方案1】:

让我们将您的验证功能简化为:

function confirmDelete(){
  return confirm("Are you Sure You want to delete this Manufacturer?");
}

那么你的带有OnClientClick 属性的按钮将类似于

OnClientClick=" return confirmDelete()"  

只要您的验证函数返回false .NET 就不会将您的代码提交给服务器。

【讨论】:

  • 好的。因此,如果我这样做并且它确实返回 true,那么调用后端函数的下一步是什么?你能解释一下如何调用后端函数吗?
  • 如果它返回 true,它将执行后面代码中出现的 OnClick 代码。看起来应该是OnClick='btnDelete_Click'
  • 哇哇哇哇。有用。 Dalorzo 的声望值得升级。保持简单愚蠢的原则有时会起作用。谢谢百万人。
  • 哇。有用。感谢一百万 Dalorzo。 Haber un buena mannana。
  • 客户端点击代码首先被执行,即Javascript前端函数。如果它返回 true,则会自动调用 Onclick 函数,这通常是后端代码隐藏函数。简而言之,您应该回答问题。让我印象深刻的是互联网上的垃圾数量,而没有人直接回答这个问题。希望这可以帮助一百万人。
【解决方案2】:

为了让人们了解如何从客户端 Javascript 调用后端函数,我想用我自己的话把答案放在这里 -> 简单明了的英语: 步 1.编写你的Javascript函数并将其放在客户端并启用脚本,这里不做太多细节。示例见下面的代码sn-p

   <script type = "text/javascript" >
    function watchdelete() 
    {
        return confirm("Are you Sure You want to delete this Manufacturer?");
    }
  1. 编写您的按钮或控件前端代码,并确保您的 OnClientClick = 您要调用的 javascript 函数的名称加上它前面的单词 return,如示例 asp 原帖中显示的代码。

  2. 确保像往常一样启动后端 C# 函数,例如双击 Visual Studio 2012 或 2013 的设计视图中的按钮或控件或其他任何东西,以便在后面的代码中自动构建其后端函数页面并为您的后端功能编写代码,以明确您希望它做什么。

  3. 正确完成第 3 步后,无论您的后端 C# 函数是什么,您都应该拥有 OnClick=。

  4. 测试您的应用程序。一旦你的前端 javascript 返回 true,它应该会自动启动 只要您按照原始帖子或类似内容中显示的前端代码放置了返回语句,您的后端功能即可。

只要你愿意,生活就可以变得简单。选择权在你。

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    相关资源
    最近更新 更多