-1

I am making a POST web-api call from a jQuery script, but the data is not binding. Page is null

Jquery

$("document").ready(function(){
    myTimer= setInterval( "StartTimer()", 1000);
});
function StartTimer()
{
    $.ajax({
        type: 'POST',
        contentType: "application/x-www-form-urlencoded",
        url: "/api/sitehit/LogHit/",  //method Name 
        data:  'Page=test' ,
        dataType: 'text/plain',
        error: function (msg) {
            alert(msg.responsetext);
        }
    }).fail(function () {
        alert("error logging hit");
    }).success(function () {
        alert("success logging hit");
    });
    clearInterval(myTimer);
}

C# code

public class SiteHitController : ApiController
{
    [HttpPost]
    public void LogHit(string Page)  // Page not binding
    {
        var c= Page; // Page is null
    }
}
3
  • Not helpful. I am invoking API/Controller/Action/StringData but still no result Commented Jan 20, 2019 at 19:03
  • Have a look at stackoverflow.com/questions/19093603/simple-post-to-web-api.. Commented Jan 21, 2019 at 14:30
  • Also make sure that your routing setup is correct, since there is not route attribute specified for methods... Commented Jan 21, 2019 at 14:31

2 Answers 2

2

There is no route set for /api/sitehit/LogHit in the controller. ApiControllers don't work the same way as regular MVC controllers. The name of the action is not the route of the endpoint, unless you specify it.

You could add route attribute to the controller action.

[Route("LogHit")]
[HttpPost]
public void LogHit(string Page)
{
}

Or (assuming there are no other HttpPost methods on the controller) change the jQuery url to url: '/api/sitehit'.

There are multiple ways to bind the data, depending on which content type you want to send. Assuming you want to use JSON you can do something like the following.

Create a model to bind to and add [FromBody] to the controller action parameter:

public class MyModelDto
{
    public string Page { get; set; }
}

[Route("LogHit")]
[HttpPost]
public void LogHit([FromBody] MyModelDto model) // add FromBody here
{
    // model.Page will contain "test"
}

Then make sure you're sending JSON in the ajax call by using JSON.stringify() to stringify the data.

$.ajax({
    type: 'POST',
    contentType: "application/json",
    url: "/api/sitehit/LogHit",
    data: JSON.stringify({Page: 'test'}),  // use JSON.stringify()
    dataType: 'json',
    success: function (data) {
        // can use response data here
        alert("success logging hit");
    },
    error: function (msg) {
        alert(msg.responsetext);
    }
});

This should correctly bind to your controller now.

If you're sending form data x-www-form-urlencoded then use [FromForm] instead and you don't need to use JSON.stringify(), but in this case the parameters should be sent in query string form: page=test&prop2=test2.

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

How to bind, please share complete information not partial. I am now using ` contentType: "application/x-www-form-urlencoded", url: "/api/sitehit/LogHit/" ` and now its hitting but data is not binding
@Sujoy updated answer. There are multiple ways to bind, depending on content type. Use [FromBody] for JSON or [FromForm] if it's form data.
Why do you make things complicated. I just want to bind it as string, because my controller-action accepts string. Moreover, it is not an issue of route because my code works well with integer parameter.
Of course everyone knows it's possible, but the question is 'how'. Your answer is not adequate. I modified the question, you may try once again.
Thanks, I did not ask for different ways. I was looking for the simplest way, probably with string. I found a simple way myself.
0

Following code worked:

    $.ajax({
        type: 'POST',
        //contentType: "application/json; charset=utf-8",
        url: "/api/sitehit/LogHit?Page=" + window.location.href,   
        //dataType: 'json',
        error: function (msg) {
            alert(msg.responsetext);
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.