[Solved] jQuery Ajax sends null parameter to Controller action in ASP.Net MVC

shoaibshafiqahmed
 
on Jul 20, 2021 03:55 AM
Sample_119964.zip
1534 Views

Hi,

i have created a modal popup to fetch data through id from view to controller but ID reflecting null values

Add to cart controller code

public ActionResult AddtoCart(int? id)
{
    ProductsWidgetsViewModels model = new ProductsWidgetsViewModels();
    model.adCartProd = entities.Tbl_Product.Where(x => x.ProductId == id).SingleOrDefault();
    //Tbl_Product p = entities.Tbl_Product.Where(x => x.ProductId == id).SingleOrDefault();
    return PartialView(model);
}
 
List<cart> li = new List<cart>();
[HttpPost]
 
public ActionResult AddtoCartp(Tbl_Product pi, string qty, int? id)
{
    Tbl_Product p = entities.Tbl_Product.Where(x => x.ProductId == id).SingleOrDefault();
    cart c = new cart();
    c.ProductId = p.ProductId;
    c.Price = (float)p.Price;
    c.qty = Convert.ToInt32(qty);
    c.bill = c.Price * c.qty;
    c.ProductName = p.ProductName;
    if (TempData["cart"] == null)
    {
        li.Add(c);
        TempData["cart"] = li;
    }
    else
    {
        List<cart> li2 = TempData["cart"] as List<cart>;
        int flag = 0;
        foreach (var item in li2)
        {
            if (item.ProductId == c.ProductId)
            {
                item.qty += c.qty;
                item.bill += c.bill;
                flag = 1;
            }
        }
        if (flag == 0)
        {
            li2.Add(c);
        }
 
        TempData["cart"] = li2;
    }
    TempData.Keep();
 
    //return RedirectToAction("Index");
    return Json("Success");
}

add to cart view code

@model Ecommerce_EF_DB_18May21.ViewModels.ProductsWidgetsViewModels
@{
    Layout = null;
}
<form id="AddtoCartProd">
    <div class="container" >
        <!-- The Modal -->
        @*<div class="modal fade" id="myModaladcart">*@
            <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog"  id="myModaladcart">
            @*<div class="modal-dialog modal-dialog-centered" style="top:10%;">*@
                <div class="modal-dialog modal-lg" style="top:10%;">
                    <div class="modal-content"> 
                        <!-- Modal Header -->
                        <div class="modal-header">
                            <h4 class="modal-title" style="color:maroon; margin-left:150px;font-size:18px;"><b>Enter Quantity for adding in Cart...</b></h4>
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                        </div> 
                        <!-- Modal body -->
                        <div class="modal-body">
                            <div class="container-fluid">
                                <div class="row"> 
                                    <div class="col-md-6">
                                        <div class="col-lg-12 col-md-12 col-sm-12 imgbox">
                                            <img id="myimage" style="min-height:200px;width:350px;height:550px;" src="@Url.Content(Model.adCartProd.ImageURL)" />
                                        </div>
                                        <br />
                                    </div> 
                                    <div class="col-md-6 ml-auto">
                                        <div>
                                            <div class="col-lg-12 col-md-2 col-sm-2">
                                                <input type="text" value="@Model.adCartProd.ProductId" id="pid" name="ProductId"/>
                                                <h1>Product Name: </h1>
                                                <br />
                                                <h1><span id="pname">@Model.adCartProd.ProductName</span></h1>
                                                <br />
                                                <h2>Price: <span id="pprice">@Model.adCartProd.Price</span> PKR</h2>
                                                <br />
                                                <h5>Color: @Model.adCartProd.color</h5>
                                                <br />
                                                <h5>Size: @Model.adCartProd.size</h5>
                                                <br />
                                                <h6>Description: @Model.adCartProd.Description</h6>
                                            </div>
                                        </div> 
                                        <br />
                                        <div class="form-group ">
                                            <label style="color:maroon"><span style="color:red">*</span> Qty</label>
                                            <input type="number" class="form-control col-md-4" name="qty" value="1" id="qty" min="1" max="100" />
                                        </div>
                                    </div> 
                                    <br />
                                </div>
                                </div>
                            </div> 
                        <!-- Modal footer -->
                        <div class="modal-footer">
                            <button id="SaveBtnPro" type="button" class="btn btn-primary" data-dismiss="modal">Save</button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal" onClick="window.location.reload();">Close</button>
                        </div> 
                    </div>
                </div>
        </div>
    </div>
 </form>
@*<script src="~/Content/javascript/jquery.min.js"></script>*@
@*<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>*@
<script type="text/javascript">
 
    //For Update Product
    $(function () {
        $("[id*=SaveBtnPro]").click(function () {
            var prod = {};
            prod.ProductId = $('[id*=pid]').val();
            prod.ProductName = $('[id*=pname]').val();
            prod.Price = $('[id*=pprice]').val();
            prod.Quantity = $('[id*=qty]').val();
            debugger;
            alert("1");
            $.ajax({
                type: 'POST',
                url: '/Widgets/AddtoCartp',
                data: JSON.stringify(prod),
                contentType: "application/json; charset=utf-8",
                dataType: "html",
            }).done(function (response) {
                alert("2");
                debugger;
                window.location.href = "/Home/Index";
                alert("3");
            }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            });
        });
    });
</script>

please help

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 28, 2021 06:26 AM
shoaibshafiqahmed says:
data: JSON.stringify(prod),

You are passing only model to the ActionResult.

You need to send the qty and id aswell.

Create a class and define the property with model and use that class to pass to the ActionResult.

public class Data
{
    public ProductsWidgetsViewModels Product { get; set; }
    public string qty { get; set; }
    public int? id { get; set; }
}

Controller

public ActionResult AddtoCartp(Data data)
{
}

JavaScript

<script type="text/javascript">
    $(function () {
        $("[id*=SaveBtnPro]").click(function () {
            var data = {};
            data.qty = "10";
            data.id = 1;

            var prod = {};
            prod.ProductId = $('[id*=pid]').val();
            prod.ProductName = $('[id*=pname]').val();
            prod.Price = $('[id*=pprice]').val();
            prod.Quantity = $('[id*=qty]').val();

            data.Product = prod;
            $.ajax({
                type: 'POST',
                url: '/Widgets/AddtoCartp',
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            }).done(function (response) {
                window.location.href = "/Home/Index";
            }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                alert(response.responseText);
            });
        });
    });
</script>