C# 在 asp.net mvc 中对控制器进行简单的 Ajax 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16186083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a Simple Ajax call to controller in asp.net mvc
提问by chamara
I'm trying to get started with ASP.NET MVC Ajax calls.
我正在尝试开始使用 ASP.NET MVC Ajax 调用。
Controller:
控制器:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
View:
看法:
<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.
我只需要使用返回数据的控制器方法打印警报。上面的代码只是在我的视图中打印“chamara”。警报未触发。
UPDATE
更新
I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working
我修改了我的控制器,如下所示,它开始工作。我不清楚为什么它现在有效。有的请解释一下。参数“a”不相关我添加了它,因为我无法添加具有相同方法名称和参数的两个方法。我认为这可能不是解决方案,但它的工作原理
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
采纳答案by asb
After the update you have done,
完成更新后,
- its first calling the FirstAjax action with default HttpGet request and renders the blank Html view . (Earlier you were not having it)
- later on loading of DOM elements of that view your Ajax call get fired and displays alert.
- 它首先使用默认的 HttpGet 请求调用 FirstAjax 操作并呈现空白的 Html 视图。(之前你没有它)
- 稍后加载该视图的 DOM 元素时,您的 Ajax 调用将被触发并显示警报。
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
早些时候,您只是将 JSON 返回到浏览器而不呈现任何 HTML。现在它呈现了一个 HTML 视图,它可以在其中获取您的 JSON 数据。
You can't directly render JSON its plain data not HTML.
您不能直接将 JSON 呈现为纯数据而不是 HTML。
回答by Darren
Remove the data attribute as you are not POSTINGanything to the server (Your controller does not expect any parameters).
删除 data 属性,因为您POSTING对服务器没有任何意义(您的控制器不需要任何参数)。
And in your AJAX Method you can use Razorand use @Url.Actionrather than a static string:
在您的 AJAX 方法中,您可以使用Razor和使用@Url.Action而不是静态字符串:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
从您的更新:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
回答by swapneel
instead of url: serviceURL,use
而不是url: serviceURL,使用
url: '<%= serviceURL%>',
and are you passing 2 parameters to successFunc?
您是否将 2 个参数传递给 successFunc?
function successFunc(data)
{
alert(data);
}
回答by Yashh
Add "JsonValueProviderFactory" in global.asax :
在 global.asax 中添加“JsonValueProviderFactory”:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
回答by RGR
It's for your UPDATE question.
这是您的 UPDATE 问题。
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
由于您不能有两个具有相同名称和签名的方法,因此您必须使用 ActionName 属性:
UPDATE:
更新:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
And please refer thislink for further reference of how a method becomes an action. Very good reference though.
请参阅此链接以进一步了解方法如何成为操作。不过很好的参考。
回答by Lokesh_Ram
First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..
首先,不需要在一个页面中包含两个不同版本的 jquery 库,“1.9.1”或“2.0.0”足以使 ajax 调用工作。
Here is your controller code:
这是您的控制器代码:
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
This is how your view should look like:
这是您的视图的样子:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "../../Home/FirstAjax",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
});
</script>
回答by gdmanandamohon
Use a Razor to dynamically change your URL by calling your action like this:
通过调用您的操作,使用 Razor 动态更改您的 URL:
$.ajax({
type: "POST",
url: '@Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
回答by oyenigun
View;
看法;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Controller Method;
控制器方法;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
回答by Hafiz Asad
If you just need to hit C# Method on in your Ajax Call you just need to pass two matter type and url if your request is get then you just need to specify the url only. please follow the code below it's working fine.
如果你只需要在你的 Ajax 调用中点击 C# 方法,你只需要传递两个事件类型和 url,如果你的请求是 get,那么你只需要指定 url。请按照下面的代码它工作正常。
C# Code:
C# 代码:
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Java Script Code if Get Request
获取请求时的 Java 脚本代码
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
Java Script Code if Post Request and also [HttpGet] to [HttpPost]
如果发布请求以及 [HttpGet] 到 [HttpPost] 的 Java 脚本代码
$.ajax({
url: 'home/FirstAjax',
type:'POST',
success: function(responce){ alert(responce)},
error: function(responce){ alert(responce)}
});
Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like url: 'FirstAjax',
注意:如果您的 FirstAjax 与您的视图控制器在同一个控制器中,则 url 中不需要控制器名称。喜欢url: 'FirstAjax',

