Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX call to async Task<string> successfully hit the method but returns failed

I have an MVC controller (not api controller) [HttpPost] method public async Task<string> PostDocument() to which I'm making an ajax call from client. And that method is making another API call to an [HttpPost] method PostDocument(DocRepoViewModel docRepo). Below is my code:

public async Task<string> PostAdminUploadData()
{
    HttpResponseMessage response = null;
    //set the parameter docRepo (a complex object)
    try {
        using (var client = new HttpClient())
        {
            string uri = documentRepositoryApiUrl + Constants.PostDoc;
            client.BaseAddress = new Uri(documentRepositoryApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            response = await client.PostAsJsonAsync(Constants.PostDoc, docRepo); //docRepo parameter for API method
        }
    }
    catch (Exception ex){}

    return (await response.Content.ReadAsAsync<string>());
}

Now in the above code response = await client.PostAsJsonAsync(Constants.PostDoc, docRepo); code piece returns success to response var (because its doing what I expected) but when the above method responds, the responds is always caught in error: in ajax bellow my ajax:

$.ajax({
    url: url,
    type: 'Post',
    data: data,
    cache: false,
    dataType: 'json',
    async: true,
    contentType: false,
    processData: false,
    success: function (data) {
        alert("pass");
    },
    error: function (data) {
        alert("field"); //always failed
    }
});

There is no exception thrown anywhere c#. Please help me to solve the problem

like image 304
Rahul Chakrabarty Avatar asked Feb 05 '15 11:02

Rahul Chakrabarty


1 Answers

I ran into a similar problem. First off, change your ajax request so the dataType is removed and the contentType is specified:

// dataType: "json",
contentType: "application/json",

Then, try changing the return type of the action to a Task<ActionResult>, and using one of the common methods on Controller, such as:

return Json(/* valid json string content */) 

or

return Content(/* read content as a string here */)

The reason for this is that WebApi controllers get a serialisation layer wrapped around to convert the result to the client's requested format. Conversely, MVC controllers are expected to call a method which returns some kind of action result (usually a view or something similar) to the view engine...

Whilst I was attempting to return a particular model, all I was receiving on the JavaScript end was the fully qualified name of the Type of that object.

Another option might be to to decorate your action with the [AcceptAjax] attribute or something similar, which I believe allows that action to reply to an ajax request.

like image 184
Hoecuspocus Avatar answered Oct 17 '22 21:10

Hoecuspocus