简体   繁体   English

如何从asp.net内的js函数调用c#函数?

[英]How to call c# function from js function inside asp.net?

I am developing my first website in vs using asp.net and c#. 我正在使用ASP.NET和C#在vs中开发我的第一个网站。 How can I call c# function from js function inside asp.net? 我如何从asp.net中的js函数调用c#函数? I want to insert form data into sql database. 我想将表单数据插入sql数据库。

C# (add_project.aspx.cs): C#(add_project.aspx.cs):

using System.Web.Services;
public partial class add_project : System.Web.UI.Page
{
[WebMethod]    
public static void InsertIntoDatabase(string projectname, string piname)
    {
        Console.WriteLine("hello");// this doesn't appear which mean it doesn't enter this function
        SqlConnection conn = new SqlConnection("Data Source=servername;Initial Catalog=databasename;Integrated Security=SSPI");
        string sql = "INSERT INTO Projects (project_name, principal_investigator) VALUES (@project_name,@pi_name)";

        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@project_name", System.Data.SqlDbType.VarChar, 50);
            param[1] = new SqlParameter("@principal_investigator", System.Data.SqlDbType.VarChar, 50);
        param[0].Value = projectname;
            param[1].Value = piname;
            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }

    }
}

js in the aspx file (add_project.aspx): aspx文件(add_project.aspx)中的js:

<script>
  function doSomething() {

      var $projectname = $("#project_name").val();
      var $piname = $("#pi_name").val();
      alert($piname);    // This alert appear
      $.ajax({
          type: "POST",
          url: 'add_project.aspx/InsertIntoDatabase',
          data: "{'projectname':'" + $projectname + "', 'piname':'" + $piname + "' }", //Pass the parameter names and values
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (msg) {
              alert('success');
          },
          error: function (e) {
              alert('error');       // this msg appear
          }
      });
         }

form in the aspx file (add_project.aspx): aspx文件(add_project.aspx)中的表单:

    <form class="form-horizontal form-label-left" id="add_project_form" runat="server" onsubmit="doSomething();">
    <div id="wizard" class="form_wizard wizard_horizontal">
<!-- Project Name -->
                          <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="project_name">Project Name <span class="required">*</span>
                            </label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                              <asp:TextBox id="project_name" required="required" class="form-control col-md-7 col-xs-12" runat="server"></asp:TextBox>
                            </div>
                          </div>
<!-- PI name -->
                          <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="pi_name">PI Name <span class="required">*</span>
                            </label>
                            <div class="col-md-6 col-sm-6 col-xs-12">
                              <asp:TextBox id="pi_name" required="required" class="form-control col-md-7 col-xs-12" runat="server"></asp:TextBox>
                            </div>
                          </div>
    </div>
</form>

I don't have access to the submit button of the form (because I use bootstrap template) . 我无权访问表单的“提交”按钮(因为我使用了bootstrap模板)。

Thanks 谢谢

Solution: I solve the problem by put [WebMethod] before the c# function Also, I were have error syntax in the insert statement. 解决方案:我通过将[WebMethod]放在c#函数之前解决了该问题。此外,我在insert语句中有错误语法。 Thanks @Pawan and all for the help. 感谢@Pawan和所有人的帮助。

the c# method should be a webmethod . c#方法应为webmethod。

[WebMethod]

here goes your c# method 这是您的C#方法

you need to import system.web.services into your code first , 您需要先将system.web.services导入代码中,

using System.Web.Services;

and write the js function into the form submit event ( if you cant access submit button) 并将js函数写入表单Submit事件(如果您无法访问Submit按钮)

write onsubmit="yourfun()" inline in the form 内联形式写onsubmit="yourfun()"

or if you are using jquery 或者如果您正在使用jQuery

$("#form-id").submit(function(){

    your function;

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET C#中调用jquery函数调用? - how to call jquery function call in asp.net c#? 如何在JavaScript文件中调用SQL函数? ASP.NET C# - How to call a sql function inside a javascript file? asp.net c# 如何从ASP.NET中的前端Javascript函数调用后端C#函数 - How to call a backend C# function from front end Javascript function in ASP.NET 如何在asp.net中调用JS函数 - How to call JS function in asp.net 如何从ASP.net中的Javascript调用C#服务器端函数 - How to call C# server side function from Javascript in ASP.net 在JavaScript脚本中将img HTML标记与对C#函数的调用相结合添加到ASP.NET页面 - Adding an img HTML tag combined with a call to C# function to an ASP.NET page inside JavaScript script 如何从javascript函数使用一些变量参数调用asp.net C#函数,并从C#函数获取字符串返回? - How to call asp.net C# function from javascript function with some variables arguments and getting string return from C# function? 无法通过ASP.NET中的JavaScript调用ac#函数 - Not able to call a c# function through javascript in asp.net 未从C#函数ASP.Net触发Javascript函数 - Javascript Function Not Firing from C# Function ASP.Net 调用 JavaScript function 从 Z1848E732214CCE460F9B24FE0C28 视图中的 C# 代码 - Call a JavaScript function from C# code in asp.net core 5 MVC view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM