Search code examples
jqueryjsonajaxasp.net-mvcparse-error

Getting parseerror on my ajax result return


I am not sure why i am getting parse error. I am setting the dataType dynamically on my ajax and when i call it with json as the dataType, i get a parse error.

MVC controller action

    public ProductViewModel UpdateProduct(ProductViewModel product)
    {
        var productContract = Mapper.Map<ProductViewModel, ProductContract>(product);
        var productReturned = _productService.UpdateProduct(productContract);

        if (productReturned.HasValue)
        {
            return Mapper.Map<ProductContract, ProductViewModel>(productReturned.Value);
        }
        return null;
    }

Ajax call

var ajaxCall = function (destinationUrl, dataToPost, ajaxDataType, element, callbackFunction) {
    $.ajax({
        url: destinationUrl,
        data: dataToPost,
        contentType: "application/json",
        dataType: ajaxDataType,
        success: function (data) {
            callbackFunction(data, element);
        },
        error: function (req, status, errorObj) {
            console.log(status);
        }
    });
}

callbackFunction

This is the method that runs on the ajax success, my database is update successfully but i need the data returned to updated the UI. I have trying getting it like data, data.d and data.d[0]

function updateProductRow(data, element) {
    console.log(data.d[0]);
}

Solution

  • I figured it out, in the case of ASP.NET MVC application with the controller action, I just had to have an attribute above my method to accept verb which will be a post. And also to convert the return type to a JSON result.

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateProduct(ProductViewModel product)
        {
            var productContract = Mapper.Map<ProductViewModel, ProductContract>(product);
            var productReturned = _productService.UpdateProduct(productContract);
    
            if (productReturned.HasValue)
            {
                return Json(Mapper.Map<ProductContract, ProductViewModel>(productReturned.Value));
            }
            return null;
        }