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

时间:2017-03-22 06:45:04

标签: javascript c# jquery asp.net twitter-bootstrap

我正在使用asp.net和c#开发我的第一个网站。 如何从asp.net中的js函数调用c#函数?我想将表单数据插入到sql数据库中。

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();
        }

    }
}
aspx文件中的

js(add_project.aspx):

<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
          }
      });
         }

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>

我无法访问表单的提交按钮(因为我使用了bootstrap模板)。

由于

解决方案: 我通过将[WebMethod]放在c#函数之前来解决问题 另外,我在insert语句中有错误语法。 谢谢@Pawan和所有人的帮助。

1 个答案:

答案 0 :(得分:1)

c#方法应该是一种web方法。

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataSearch current=data.get(position);
    myHolder.textsanctname.setText(current.sanctname);
    myHolder.textstate.setText("State " + current.state);
    myHolder.textType.setText("Category " + current.catagory);
    myHolder.textsanctname.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, current.sanctname +" " +current.state+ " "+current.catagory,Toast.LENGTH_SHORT).show();
        }
    });

}

这里是你的c#方法

您需要先将[WebMethod] 导入代码

system.web.services

并将using System.Web.Services; 函数写入表单提交事件(如果您无法访问提交按钮)

的形式内联js

或者如果您使用的是jquery

onsubmit="yourfun()"