Leroi
Leroi

Reputation: 369

How to send static html data over a web api in asp.net?

I have a product page developed in ASP.NET which I hard coded the values of the products and at the moment is just frontend. On this page, I have product information like Product name and price and a Add to cart button below these items on the page. I have a web api which I would like to send this product information over. For test purposes, it works when I am using an input form but I will like to know how to send these static info like name and the price when I click the button. Below is my html page

<div class="col-md-3 col-sm-3 col-xs-6" style="margin-bottom: 8px;">
    <div class="img-thumbnail product-item" style="height: 300px;">
        <img class="img-fluid" title="Click to View Product detail" style="cursor: pointer; height: 160px; width: 100%;" src="~/Images/SamsungNote.JPG" />
        <div class="caption">
            <h5>Samsung note 10 plus</h5>
            <p>€ 1071.28</p>
            <p>
                Available <button class="pull-right" href="#"><i class="fa fa-shopping-cart"> Add to cart</i></button>
            </p>
            <div class="product-item-badge">New</div>
        </div>
    </div>
</div>

And In my HomeController, I have the following. Like I said earlier, this works with forms but is there any way i can send this product info when I click on the Add to cart button?

 [HttpPost]
        public ActionResult AddToCart(Product product)
        {
            using (var client =  new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:60036/");
                var content = new StringContent(
                    JsonConvert.SerializeObject(product),
                    Encoding.UTF8,
                    MediaTypeNames.Application.Json);
                var postTask = client.PostAsync("api/Product", content);
                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return this.RedirectToAction("Home");
                }
            }

            this.ModelState.AddModelError(string.Empty, "Server error. Please contact your administrator");

            return RedirectToAction("Privacy", "Home");
        }

Upvotes: 3

Views: 1518

Answers (2)

Zhi Lv
Zhi Lv

Reputation: 21656

You could use JQuery to find the <h5> and <p> elements and get the product information, and then use Ajax method to submit the data to the action method:

Sample code as below:

<div class="col-md-6 col-sm-6 col-xs-6" style="margin-bottom: 8px;">
    <div class="img-thumbnail product-item" style="height: 300px;">
        <img class="img-fluid" title="Click to View Product detail" style="cursor: pointer; height: 160px; width: 100%;" src="~/images/Image1.jpg" />
        <div class="caption">
            <h5>Samsung note 10 plus</h5>
            <p>€ 1071.28</p>
            <p>
                Available <button class="pull-right btn-addToCart" href="#"><i class="fa fa-shopping-cart"> Add to cart</i></button>
            </p>
            <div class="product-item-badge">New</div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(function () { 
        $(".btn-addToCart").click(function () { 
            //prevent the default event.
            event.preventDefault();
            //create a object to store the entered value.
            var Product = {};
            //using jquery to get the product information.
            Product.ProductName = $(this).closest(".caption").find("h5").html();
            Product.Price = $(this).closest(".caption").find("p:first").html();
 
            $.ajax({
                type: "POST",
                url: "/Home/AddToCart",  //remember change the controller to your owns. 
                data: Product,
                success: function (data) {
                    console.log(data)
                }, 
                error: function (response) {
                    console.log(response.responseText);
                }
            });

        });
    });
</script>

Then, the debugger screenshot like this:

enter image description here

Edit:

The Product model:

public class Product
{
    public string ProductName { get; set; }
    public string Price { get; set; }
}

Upvotes: 1

Li-Jyu Gao
Li-Jyu Gao

Reputation: 940

Use some JS library (like jQuery) to do AJAX.

For example:

$.ajax({
    url: 'http://yourdomain/Home/AddToCart',
    data: {'ProductName': 'Samsung', 'Price': 1071.28},
    type: "POST",
    dataType: "json",
    contentType: "application/json;charset=utf-8",
    success: function(returnData){
        console.log(returnData);
    },
    error: function(xhr, ajaxOptions, thrownError){
        console.log(xhr.status);
        console.log(thrownError);
    }
});

Upvotes: 1

Related Questions