0

I wrote the following code for calling the API from client script.

Cshtml

<button class="btn btn-link btn-sm js-toggleFollowing" data-user-id="@gig.ArtistId">Follow</button>

API Call:

$(".js-toggleFollowing").click(function (e)
{
    var button = (e.target);

    $.post("/api/followings", { followeeId: button.attr("data-user-id") })
    .done(function ()
    {
        button.text("Following");
    })
    .fail(function ()
    {
        alert("Something failed");
    })
});

API Controller Method

// Code for api call

[HttpPost]
public IHttpActionResult Follow(FollowingDto dto)
{
    var userId = User.Identity.GetUserId();

    if (_context.Followings.Any(f => f.FolloweeId == userId && f.FolloweeId == dto.FolloweeId.ToString()))
        return BadRequest("The Following alreday exists.");

    var following = new Following
    {
        FollowerId = dto.FolloweeId.ToString(),
        FolloweeId = userId
    };

    _context.Followings.Add(following);
    _context.SaveChanges();

    return Ok();
}

DTO Class:

public class FollowingDto
{
    public int FolloweeId { get; set; }
}

API call is working with postman without converting the parameter to DTO. But it is not working when i use the dto as a parameter. dto class is also copied.

Please help me to resolve this issue.

Shidersz
  • 16,846
  • 2
  • 23
  • 48
PCDev
  • 59
  • 6
  • Did you enable camel case? Where is your route mapping? /api/followings? – wannadream Oct 29 '18 at 01:45
  • what mean by no able to call? any error? can u do a log inside the button and inside the ajax too? n also open the developer console check the network tab whether click it did fire? – Se0ng11 Oct 29 '18 at 01:46
  • Normally, the post's parameters will be sent through the request's body so you should add [FromBody] to make sure that it will be mapped correctly `public IHttpActionResult Follow([FromBody] FollowingDto dto)` – Dinh Tran Oct 29 '18 at 02:09
  • 3
    You're missing a `$` here `var button = (e.target);` before the open bracket. – Musa Oct 29 '18 at 02:42
  • @Hooman Thanks for the reply. Now call worked but getting followeeId as null in the controller class. How followeeId will get converted to FollowingDto. What else am i missing in code? – PCDev Oct 29 '18 at 05:18
  • 1
    your button needs to be a jQuery object, before you can use attr() function. try this: var button = $(e.target). Thats what Musa has told you as well. – Hooman Bahreini Oct 29 '18 at 05:35
  • 1
    @Hooman Thanks very much. – PCDev Oct 29 '18 at 09:35
  • Thanks all for the valuable comments. – PCDev Oct 29 '18 at 09:35

0 Answers0