Home > Net >  How can i pass Multiple Parameters to jQuery ajax call with datatype HTML
How can i pass Multiple Parameters to jQuery ajax call with datatype HTML

Time:01-10

I have the following jquery code to call a POST method in Asp.net core Controller

 $.ajax({
            url: '@Url.Action("GetItemsForRelease", "PointOfSales")',
            data: { requestModel: TFObj },
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function (responsedata) {
                $("#releaseItemsPush").html(responsedata);
            },
            error: function (error) {
                console.log(error);
            }
        });

but following controller action shows null object

[HttpPost]
public ActionResult GetItemsForRelease(RequestModel requestModel)
{
  return PartialView("_partialReleaseItem", requestModel);
}

CodePudding user response:

Following controller action shows null object

Well, as per your shared code snippet contentType: "application/json; charset=utf-8 casuing null data on your controller it because you have define dataType as html but contentType: "application/json; charset=utf-8",. When we send html as dataType it would treat as text here in controller thus posted data has lost due to mismatched data type.

Let's assume you have following model:

Model:

public class RequestModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

Ajax:

            var TFObj = {};
            TFObj.Id = 1; // You can get HTML as $('#Id').val()
            TFObj.Name = "Test Name";
            TFObj.Email = "Test Email";
            console.log(TFObj);

            $.ajax({
                url: "/PointOfSales/GetItemsForRelease",
                type: "POST",
                data: { requestModel: TFObj },
                dataType: "html",
                success: function (responsedata) {
                    $("#releaseItemsPush").html(responsedata);
                },
                error: function (error) {
                    console.log(error);
                }
            });

Note: Make sure, you data has been posted accordingly from your browser, by checking console as following:

enter image description here

Controller:

        [HttpPost]
        public ActionResult GetItemsForRelease(RequestModel requestModel)
        {
            return PartialView("_partialReleaseItem", requestModel);
        }

Output:

enter image description here

Note: You can see we are getting data in controller. So just get rid of your contentType would resolve your null data.

  • Related