jquery ajax调用控制器发布空字符串

时间:2014-03-28 06:52:36

标签: jquery ajax asp.net-mvc-4 post

我从jquery ajax post发布了一个车辆的id到控制器.Ajax调用是调用控制器方法但是该字符串总是为null。我在web上搜索了很多但是任何解决方案都没有工作。在视图中有值但是null在controller.please帮助我。

这是我的代码: 图

          <script type="text/javascript">
           function DeleteVehicle(id) {
          alert("working");
          if (confirm("Do you want to delete vehicle: " + id)) {
      //  var requestData = { 'vehicleId': vid }
        var dataPost={'id':id}
        $.ajax({



            url: '@Url.Action("DeleteVehicle", "Vehicle")',
            type: 'POST',
            data: dataPost,
            success: function (data) {
                alert("Success, sent data to controller");
            },
            error: function (data) {
                    alert("Error: " + data.responseText);
                }

        });
    }
}

$(function () {//when the document is ready
    $("#Delete").click(DeleteVehicle);
});

控制器

        public ActionResult DeleteVehicle(string id)
        {

            //code
               return Json(id, JsonRequestBehavior.AllowGet);
       }

3 个答案:

答案 0 :(得分:2)

你有把httppost属性放在动作方法上,如下所示?

[httpPost]
 public ActionResult DeleteVehicle(string id)
        {

            //code
               return Json(id, JsonRequestBehavior.AllowGet);
       }

和jquery

  $(document).ready(function() {
        $("#Delete").on("click",  function(){
       var id = $(this).).attr("id"); ////fetch id wherever you are fetching
       alert("working");
              if (confirm("Do you want to delete vehicle: " + id)) {
          //  var requestData = { 'vehicleId': vid }
            var dataPost={'id':id}
            $.ajax({



                url: '@Url.Action("DeleteVehicle", "Vehicle")',
                type: 'POST',
                data: dataPost,
                success: function (data) {
                    alert("Success, sent data to controller");
                },
                error: function (data) {
                        alert("Error: " + data.responseText);
                    }

            });
        }


    });

有关详细信息,请查看此

MVC Deleting record using Javascript pop up

答案 1 :(得分:1)

var dataPost应为字符串,类似var dataPost = '{"id":"' + id + '"}'$.ajax的其他设置如下 - &gt;

contentType: "application/json; charset=utf-8",
dataType: "json",

答案 2 :(得分:0)

尝试在您的操作中添加[HttpPost]属性,然后重试。