请在MVC 4使用$阿贾克斯AJAX请求 [英] Make an AJAX request using $.ajax in MVC 4
问题描述
我试图在MVC 4剃刀使用$阿贾克斯AJAX请求。我不知道如何实现它。
使用这个视频我能成功地做出了返回的数据链路驱动的电话,但我可以不像是会从一个jQuery函数里面做同样的事情。我似乎无法找到如何做到这一点的任何基本的例子。 这是我与我的工作:
HomeController.cs
公共字符串测试(){
返回它的工作原理;
}
View.cshtml
功能盘点(dealerID){
$阿贾克斯({
网址:@ Url.Action(HomeController中,测试),
数据:{dealerID:dealerID},
键入:POST,
成功:功能(数据){
处理(数据);
}
});
}
您只需要使它成为的ActionResult
。另外,如果您使用的是Ajax的POST,则动作必须标有 HttpPost
属性。试试这个:
[HttpPost]
公众的ActionResult测试(字符串dealerID)
{
返回的内容(它的工作原理);
}
修改其实,还有一些其他问题的语法。
-
Url.Action
有错误的顺序控制器/动作参数 - 应该是ActionName,再ControllerName - 为
Url.Action
,如果控制器类是HomeController的,那么你只需要家 - 在jQuery的选项语法是错误的 - 应
成功:功能(数据){}
$。阿贾克斯({
网址:@ Url.Action(测试,家),
数据:{dealerID:dealerID},
键入:POST,
成功:功能(数据){
警报(数据);
}
});
I am trying to make an AJAX request using $.ajax in MVC 4 with Razor. I'm not sure how to implement it.
Using this video I was able to successfully make a link-driven call that returned data, but I can't seem to do the same thing from inside a jquery function. I can't seem to find any basic examples of how to do this. This is what I am working with:
HomeController.cs
public string test(){
return "It works";
}
View.cshtml
function inventory(dealerID) {
$.ajax({
url: '@Url.Action("HomeController","test")',
data: {dealerID: dealerID},
type: 'POST',
success: function(data) {
process(data);
}
});
}
You just need to make it an ActionResult
. Also, if you're using an Ajax POST, then the action needs to be marked with the HttpPost
attribute. Try this:
[HttpPost]
public ActionResult test(string dealerID)
{
return Content("It works");
}
Edit Actually, there are a few other problems with the syntax.
Url.Action
has the controller/action parameters in the wrong order -- should be "ActionName" first, then "ControllerName"- For
Url.Action
, if the controller class is "HomeController", then you need just "Home" - The JQuery options syntax is wrong -- should be
success: function(data) {}
.
$.ajax({
url: '@Url.Action("test", "Home")',
data: {dealerID: dealerID},
type: 'POST',
success: function(data) {
alert(data);
}
});
这篇关于请在MVC 4使用$阿贾克斯AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!