简体   繁体   中英

how to get json data from asp.net controller using ajax in jquery

I become engage, I have a controller and in view I try to get data as json via jquery ajax. I get data as List , string , ... but as a model? no never. I used this type of code several times, but today it doesn't work. My God. Controller

[HttpPost]
    public JsonResult UpdatedShoppingCartRentalItems()
    {
        var subTotalIncludingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal;
        var shoppingCartItems = _workContext.CurrentCustomer.ShoppingCartItems;
        var model = new List<RentalMiniCart>();
        if (shoppingCartItems.Any())
        {
            foreach (var item in shoppingCartItems)
            {
                var product = _productService.GetProductById(item.ProductId);
                var row = new RentalMiniCart()
                {
                    ShoppingCartItem = item,
                    ProductSeName = product.GetSeName()
                };
                if (item.RentalStartDateUtc != null && item.RentalEndDateUtc != null)
                {
                    // rental product
                    // number of days
                    var numberofDays = 1;
                    if (item.RentalStartDateUtc != item.RentalEndDateUtc)
                    {
                        //endDate = endDate.AddDays(-1);
                        var numberOfDaysTimeSpan = item.RentalEndDateUtc - item.RentalStartDateUtc;
                        numberofDays = numberOfDaysTimeSpan.Value.Days;
                    }
                    var previousDecimalPrice = numberofDays * product.Price;
                    row.PreviousPrice = _priceFormatter.FormatPrice(previousDecimalPrice, false, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax);
                    var currentDecimalPrice = RentalSystemHelper.CalculateRentalPrice(product.Id, item.RentalStartDateUtc, item.RentalEndDateUtc);
                    row.CurrentPrice = _priceFormatter.FormatPrice(currentDecimalPrice, false, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax);
                }
                else
                {
                    row.PreviousPrice = _priceFormatter.FormatPrice(product.Price, false, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax);
                    row.CurrentPrice = _priceFormatter.FormatPrice(product.Price, false, _workContext.WorkingCurrency, _workContext.WorkingLanguage, subTotalIncludingTax);
                }
                model.Add(row);
            }
        }
        return Json(model);
    }

I used breakpoint and detect model has values, but I get error json.

My View

function CorrectMiniCartItems() {
    $.ajax({
        type: 'POST',
        url: "@Html.Raw(Url.Action("UpdatedShoppingCartRentalItems", "MiscNopshopRentalSystem"))",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        /*data: data,*/
        success: function (result) {
            console.log("success result: " + result);
            // Code goes here
        },
        error: function(result) {
            console.log("error result: "+result);

        }
        ,
        complete : function (result) {
            //console.log("complete result: " + result);
        }
    });
}

Try changing your return from

return Json(model)

to

return Json(model, JsonRequestBehavior.AllowGet)

as mentioned in comment by @JamesS, https://github.com/Tratcher/EDES/blob/a5e783cf4d1689590a07f10c1a48ffc7f0981352/EDES/Controllers/ErrorController.cs#L43

this works,

[HttpPost]
        [Authorize(AuthenticationSchemes = ApiKeyAuthDefaults.AuthenticationScheme)]
        public IActionResult Post([FromBody]JObject body)
        {
            if (body == null)
            {
                return BadRequest();
            }
            
            var report = new ErrorReport()
            {
                Created = DateTimeOffset.UtcNow,
                Message = body.GetValue("message").Value<string>(),
                Version = body.GetValue("version").Value<string>(),
                Json = body.GetValue("json").ToString(Formatting.None),
            };

            _context.ErrorReports.Add(report);
            _context.SaveChanges();

            return Ok();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM