0

我正在尝试将参数传递给我的 web api,但发布请求没有通过。它可以在没有参数的情况下正常工作,但使用一个参数是行不通的。我一直在使用相同的方法将参数传递给 MVC 操作,并且效果很好,但 api 就是不接受它。

视频控制器:

    [HttpPost]
    public void LikeVideo(uint videoID)
    {

    }

html中的链接:

<a href="@Url.Action("LikeVideo", "Video", new { httpRoute = "DefaultApi"})" class="RateVideo">

阿贾克斯请求:

    $(".RateVideo").click(function (e) {

    e.preventDefault();
    $.ajax({
        type: "POST",
        url: $(this).attr("href"),
        data: { videoID: 123},

    });

});

提前致谢

4

3 回答 3

0

如果您试图访问控制器并向其发布数据。我会使用这种结构。

 //If 123 is an external parameter passed into the function 
 var json = '{videoID: ' + 123 + '}';

 $.ajax({
     url:'@Url.Action("LikeVideo", "Video")',
     type:'POST',
     data:json,
     contentType: 'Application/json',
     success:function(result){
         //Whatever
     }
 });

您也可以使用 Json.Stringify 代替我在此处对数据所做的操作。

编辑:void 也应该是 ActionResult 或 JsonResult。不是空的

于 2018-12-13T09:31:28.587 回答
0

尝试以下语法:

$.ajax({
     url:'your url',
     type:'POST',
     data:JSON.stringify({videoID:123}),
     contentType: 'Application/json',
     success:function(result){
        //your code
     }
 });
于 2018-12-13T10:12:52.187 回答
0

终于让它工作了,我不得不像这样调整 API 操作:

    [HttpPost]
    [Route("API/Video/LikeVideo")]
    public void LikeVideo([FromBody]uint videoID)
    {

    }

并且必须像这样修改ajax:

        $.ajax({
        type: "POST",
        url: $(this).attr("href"),
        data: JSON.stringify(@Model.VideoID),
        contentType: 'Application/json',
    });

这同样有效:

    var videoID = 123;

    e.preventDefault();
    $.ajax({
        type: "POST",
        url: $(this).attr("href"),
        data: JSON.stringify(videoID),
        contentType: 'Application/json',
    });
于 2018-12-13T13:54:56.423 回答