4

I am developing my first website in vs using asp.net and c#. How can I call c# function from js function inside asp.net? I want to insert form data into sql database.

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):

<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):

    <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) .

Thanks

Solution: I solve the problem by put [WebMethod] before the c# function Also, I were have error syntax in the insert statement. Thanks @Pawan and all for the help.

13
  • remove .cs extension from url Commented Mar 22, 2017 at 6:48
  • I tried it but it doesn't work Commented Mar 22, 2017 at 6:49
  • 1
    you can use [WebMethod] attribute on your method to access it from client side Commented Mar 22, 2017 at 6:50
  • What specific error you are getting? Commented Mar 22, 2017 at 6:51
  • refere stackoverflow.com/questions/7262940/webmethod-not-being-called Commented Mar 22, 2017 at 6:51

1 Answer 1

1

the c# method should be a webmethod .

[WebMethod]

here goes your c# method

you need to import system.web.services into your code first ,

using System.Web.Services;

and write the js function into the form submit event ( if you cant access submit button)

write onsubmit="yourfun()" inline in the form

or if you are using jquery

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

    your function;

});
Sign up to request clarification or add additional context in comments.

2 Comments

I already wrote <form class="form-horizontal form-label-left" id="add_project_form" runat="server" onsubmit="doSomething();">
can you put a debugger in your c# code and check whether it hits the backend..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.