2016-08-05 59 views
-1

我是新来的MVC,并通过AJAX在我的ASP.NET应用程序的动作访问数据面临的一个问题。 这是我的Ajax代码:阿贾克斯不将数据返回到行动ASP.net MVC

$('.testBtn').click(function() { 
    $.ajax({ 
     type: 'GET', 
     data: { id: 10 }, 
     url="@Url.Action("GetData", "Consultation")", 
     success:function() 
     { 
     } 
    }); 
}); 

这里是我的控制器内的行动:

public ActionResult GetData(int id) 
{ 
    string x=id.ToStrring(); 
    return null; 
} 

为了测试我只是路过一个静态的整数,让我的行动里它的价值。

单击按钮时我收到以下错误:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetData(Int32)' in 'careshade_mvc.Controllers.ConsultationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

+0

检查你的ajax类型是GET把它改为POST并尝试 –

+0

@Div问题仍然存在.. –

+0

还有一件事你必须检查,在你的mvc方法上面添加'[HttpPost]'。 –

回答

0

这里是工作代码:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('.testBtn').click(function() { 
      $.ajax(
       { 
        url: 'Consultation/GetData', 
        type: "POST", 
        data: { id: 10 }, 
        success: function (result) { 
        } 
       }); 
     }); 
     }); 
    </script> 
</head> 
<body> 

    <input type="button" class="testBtn" value="ClickHere" name="button"> 
</body> 

</html> 
+0

喜@Div感谢。你的努力,但你的代码也不会在我结束工作单击按钮时没有任何反应 –

+0

@Bilal阿姆贾德,确保点击里面'$(文件)。就绪(函数(){});' –

0

试试这个:

$(document).ready(function() { 
     var id = 10; 
     $('.testBtn').click(function() { 
     $.ajax(
      { 
       url: 'Consultation/GetData/' + id,//instead data: { id: 10 }, 
       type: "GET", 
       success: function (result) { 
       } 
      }); 
    }); 
    }); 
+0

这将使。没有任何区别可言 –

+0

@Stephen Muecke在我的情况下smotimes它做, – Marcin

+0

不,它不需要 –

0

你需要使用一个冒号(:)字符后的url不等于(=)符号。

简单的改变:

url="@Url.Action("GetData", "Consultation")", 

要这样:

url:"@Url.Action("GetData", "Consultation")", 

这是我不得不作出拨打电话work.Hope它可以帮助你唯一的变化!