Skip to content Skip to sidebar Skip to footer

Error While Calling Webapi In My Asp.net Project

This is my api code that return successfull json data while using get method public Question[] Get() { getQuestion obj = new AllDataAccess.getQuestion(); return obj.questio

Solution 1:

It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.

var postData = { question:$("#submit").val() };
    $.ajax({
       type: 'POST',
       contentType: "application/json; charset=utf-8",
       url: 'http://localhost:53893/api/values/post',
       data: JSON.stringify(postData),
       dataType: 'json',
       success: function (data,status) {
           console.log(status);
       },
       error: function (err) {
           console.log(err);
       }
    });

In the server side, you should create a model class for Post method;

publicclassPostInput
{
    publicstring Question { get; set; }
}

And then Post method looks like;

[HttpPost]
publicvoidPost([FromBody]PostInput input)
{
     SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
     obj.savaData(question);
}

Solution 2:

If you want to use FromBody, you can do so. JavaScript

$.ajax({
    type: "POST",
    //default content-type, could be omittedcontentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    url: 'http://localhost:53893/api/values/post',
    data: {'': $("#submit").val()}
});

API action

[HttpPost]
publicvoidPost([FromBody]string question)
{
     SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
     obj.savaData(question);
}

You had these issues.

  1. Wrong content-type for your ajax call.
  2. Data was not posted correctly.
  3. val() should be used instead of .value.
  4. API action should be decorated with [HttpPost].

Post a Comment for "Error While Calling Webapi In My Asp.net Project"