Ajax调用返回始终为空对象

时间:2019-07-19 10:53:09

标签: ajax asp.net-mvc

我知道关于这个主题有很多类似的帖子,但是我仍然无法解决我的问题。

我正在尝试通过ajax从控制器中调用带有按钮的ActioResult方法。 问题是我总是找回空对象

我很确定问题是我无法将ajax调用与“数据:”字段中的控制器绑定

AJAX呼叫:

$(document).ready(function () {
    $(".milkmilk").click(function () {

        $.ajax({
            type: "POST",
            url: '@Url.Action("GoatMilk", "User")',
            datatype: "html",
            data: { name: 'name' },
            success: function (data) {
                $(this).closest('[data-rel]').html(data);
                },
            error: function (data) {
                alert("error!");
                }
        });
    });
});

控制器:

    public ActionResult GoatMilk(string name)
    {
        var rep = new GoatRepository();
        var goat = rep.GetAnimal(name);

        if(goat != null)
        {
            var model = FarmFactory.CreateAnimalModel<GoatViewModel>(goat) as GoatViewModel;

            model.Milk = rep.MilkProduction(goat);

            _MyEchoFarmDB.Update(goat);

            var rek = new FarmRepository();
            var deposit = rek.GetDeposit(name);
            deposit.Milk = goat.Milk;
            db.Update(deposit);

            return Json(model.Milk, JsonRequestBehavior.AllowGet); 
        }
        return View();
    }

HTML代码

@foreach (var item in Model)
{
    <tbody>
       <tr>
           <td>
               <button class="milkmilk" data-rel="item.Name">MILK</button>
          </td>
      </tr>
   </tbody>
}

代码永远不会输入到if(goat!= null)内部,所以我总是返回一个错误(注意,如果没有Ajax调用,该方法就可以正常工作了

谢谢!

3 个答案:

答案 0 :(得分:0)

问题:

  1. 缺少HttpPost的控制器。
  2. 方法参数名称应与ajax传递参数匹配
  3. ajax数据格式不正确。

检查我的更新代码:

Js:

   $.ajax({
            type: "POST",
            url: '@Url.Action("GoatMilk", "User")',
            datatype: "html",
            data: {'name': _id}, //this 'id' should match with method parameter
            success: function (data) {
                 if(data != null){ 
                    //your html is not clear
                    //bind your response data with html and append to div
                    //for example
                     var html = '';
                     $.each(data, function(i,v){
                       html = '<td><button class="milkmilk" data-rel="'+i.Name+'">MILK</button></td>'
                     });

                    $(this).closest('[data-rel]').html(html);
                 }
            },
            error: function (model) {
                alert("error!");
            }
        });    

控制器:

[HttpPost]
public ActionResult GoatMilk(string name) //first check name is not null
{
    var rep = new GoatRepository();
    var goat = rep.GetAnimal(name); //debug  goat and check goat is not null

    if(goat != null)
    {
        var model = FarmFactory.CreateAnimalModel<GoatViewModel>(goat) as GoatViewModel;

        model.Milk = rep.MilkProduction(goat);

        _MyEchoFarmDB.Update(goat);

        var rek = new FarmRepository();
        var deposit = rek.GetDeposit(name);
        deposit.Milk = goat.Milk;
        db.Update(deposit);
        //assuming it returns list
        return Json(model.Milk, JsonRequestBehavior.AllowGet); 
    }
    return View();
}

答案 1 :(得分:0)

代替ActionResult尝试使用JsonResult方法返回

 public JsonResult GoatMilk()
 {
     return Json();
 }

答案 2 :(得分:0)

这可能不是解决问题的最干净的方法,但运行起来似乎很顺利

HTML:

<td>
    <button type="button" class="milk" data-rel="@item.Name">MILK</button>
    <p class="milkGoat">@item.Milk</p>
</td>

控制器:

public JsonResult GoatMilk(string name)
{
     return Json(model.Milk, JsonRequestBehavior.AllowGet); 
}

Ajax:

<script type="text/javascript">    

    $(document).ready(function () {
        $(".milk").click(function () {
            var name = $(this).data('rel');       
            var me = $(this)

            $.ajax({
                type: "POST",
                url: '@Url.Action("GoatMilk", "User")',
                datatype: "html",
                data: { name: name },
                success: function (milk) {
                    me.next(".milkGoat").html(milk);
                },
                error: function (milk) {
                    alert("error!");
                }
            });
        });
    });
</script>