.Net Better structure : With Product sample - Insert Data from JavaScript (3)

In this post we are going to call C# function using jQuery Ajax.
jQuery Ajax help to send client side request without doing a post back. This allow to trigger an asynchronous (you can do synchronous as well, but what is the point ?)

Add the jQuery libry to your page header.
Find this from Google or Microsoft CDN.

I'll take from Google CDN.

https://developers.google.com/speed/libraries/#jquery

Create a JavaScript file under folder called Scripts and name that file as Script.js.
Add the following script to that file.
Using this script file we are going to call a server side method which is written in C#.

Script.js

function AddProduct() {
    var name = document.getElementById('txtProductName').value;
    var price = document.getElementById('txtProductPrice').value;
    if (name == "") {
        alert("Enter product name !");
    }else if (price == "") {
        alert("Enter product price !");
    }else if (isNaN(price)) {
        alert("Enter an number as product price !");
    } else {
       var parameter = { "name" : name, "price" : price }

        $.ajax({
            type: "POST",
            url: "Products.aspx/AddProduct",
            data: JSON.stringify(parameter),
            contentType: 'application/json, charset=utf-8',
            dataType: 'json',
            success: function() {
                alert("Success !");
            },
            failure: function() {
                alert("Fail !");
            }
        });
    }
}

In the Products page lets add the JavaScript (js) function to the button. So when the button get clicked it will trigger the particular function in the js file.
To do that add the reference of our Script.js to the page.

Products.aspx

<head runat="server">
    <title></title>
    <script src="Scripts/Script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

Add the js function to the button's on client click event.

<td><asp:Button runat="server" ID="btnAddProduct" Text="Add Product" OnClientClick="AddProduct(); return false;"/></td>

Within the Product page's cs file lets create a static method and lets decorate with WebMethod attribute.

Products.aspx.cs

[WebMethod]
        public static void AddProduct(string name, string price)
        {
            var product = new Product {Name = name, Price = double.Parse(price)};
            //ProductHelper should be static. Non static functions are not allowed
            ProductHelper.AddProduct(product);
        }

Add the following class to the Models section.

Product.cs

namespace TestWeb.ClassFiles
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

Add the following method to a class called ProductHelper.cs

ProductHelper.cs

public static string AddProduct(Product product)
        {
            string message;
            try
            {
                var name = new SqlParameter("@name", product.Name);
                var price = new SqlParameter("@price", product.Price);

                var conn = Connection.GetConnection();
                conn.Open();

                var cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "AddProducts";

                cmd.Parameters.Add(name);
                cmd.Parameters.Add(price);

                cmd.ExecuteNonQuery();
                conn.Close();

                message = "Product Added !";
            }
            catch (Exception ex)
            {
                message = String.Format("Error: {0}", ex);
            }

            return message;
        }
    }






Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#