skip to Main Content

I am unable to receive the string on the controller side. Please help me solve the issue. I will provide code snippets to expand on the problem.

Javascript code snippet:-

var GetMyQueueSearch = utilsBusiness.GetData(GetMyQueueSearchUrl + "?iUserId=" + iUserId);
var resultObj = JSON.stringify(GetMyQueueSearch.Data);
gridData = resultObj;         //global Variable

utilsBusiness.GetData is calling an ajax request using the url inside and return data of type:-

public object Data { get; set; }
public MessageCode MCode { get; set; }
public string Message { get; set; }
public bool Success { get; set; }

Ajax request snippet:-

function ExportToExcel() {
    $.ajax({
        type: "POST",
        url: '/Home/ExportToExcel/',
        dataType: 'text',
        traditional: true,
        data: jsonData,
            beforeSend: function () {
        },
        success: function (result) {
            console.log(result);
        },
        error: function (data) {
            console.log(data);
        },
        complete: function () {
        }
    });
}

MVC side Controller code snippet:-

[HttpPost]
public ActionResult ExportToExcel(string jsonData)
{
    try
    {
        DataTable dt;
    }
}

Here jsonData is coming as null. Please help me resolve this issue.

If possible provide solution to send string only instead of changing the controller side input into a class.

2

Answers


  1. assuming jsonData is a string, you need to fix your API. There are two ways – to create text plain formatter or I recommed to use an http request body

    public async Task<ActionResult> ExportToExcel()
    {
         using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
        {  
           string jsonData= await reader.ReadToEndAsync();
        }
    }
    

    also replace " dataType: ‘text’ " with a content type

      contentType: 'text/plain',
    
    Login or Signup to reply.
  2. Usually we pass form data to controller by 2 ways:

    1. Pass form data by binding fields name with the argument name in action method.
    2. Bind form data with the model.

    In your case you are trying to send the data without binding the field name with your data.

    Try something like this:

    Ajax request snippet:-

    function ExportToExcel() {
        $.ajax({
            type: "POST",
            url: '/Home/ExportToExcel/',
            dataType: 'text',
            traditional: true,
            data: { data: jsonData }, /* Replaced data: jsonData,*/
            beforeSend: function () {
            },
            success: function (result) {
                console.log(result);
            },
            error: function (data) {
                console.log(data);
            },
            complete: function () {
            }
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search