[英]How to properly call an MVC Controller with AJAX
I am trying to make an AJAX call to an MVC controller ActionResult that I have.我正在尝试对我拥有的 MVC 控制器 ActionResult 进行 AJAX 调用。 I have used ajax before but I am new to MVC.
我以前使用过 ajax,但我是 MVC 的新手。 I have an AJAX call in a separate .js file that is triggered in an on click event attached to one of the buttons in a view.
我在一个单独的 .js 文件中有一个 AJAX 调用,该调用是在附加到视图中的一个按钮的点击事件中触发的。 The AJAX call is being triggered as expected, but always returns with a "resource not found" error.
AJAX 调用按预期触发,但总是返回“未找到资源”错误。 Code shown below:
代码如下所示:
View Button:查看按钮:
<input type="button" class="btn btn-success" value="Download Pictures" id="btnGetPics"/>
AJAX Call: AJAX 调用:
var ajaxURL = 'MMRController/TestAjax';
$('#btnGetPics').on('click',
function () {
$.ajax({
type: 'POST',
url: ajaxURL,
data: param = "this",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
console.log('firing ajax call');
},
success: function (data) {
alert(data);
},
error: function (ex) {
console.log('Error');
console.log(ex.responseText);
alert("Error downloading images. Please contact IT.");
}
});
});
ActionResult in Controller:控制器中的 ActionResult:
[HttpPost]
public ActionResult TextAjax(string param)
{
return Json(param + " works", JsonRequestBehavior.AllowGet);
}
Below is the error I am getting:以下是我收到的错误:
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
@media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
@media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/MMR/MMRController/TestAjax<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3429.0
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'MMRController' was not found on controller 'MOHR.Controllers.MMRController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Any help would be greatly appreciated.任何帮助将不胜感激。
You aren't setting the data
property correctly.您没有正确设置
data
属性。
data: param = "this"
should be应该
data: { param : "this"},
Also yyour url needs to have a forward slash before the controller ( /
) and remove the word controller
so in full...此外,您的 url 需要在控制器 (
/
) 之前有一个正斜杠,并完全删除controller
一词...
var ajaxURL = '/MMR/TestAjax';
//... etc..
$.ajax({
type: 'POST',
url: ajaxURL,
data: { param : "this"},
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
console.log('firing ajax call');
},
success: function (data) {
alert(data);
},
error: function (ex) {
console.log('Error');
console.log(ex.responseText);
alert("Error downloading images. Please contact IT.");
}
});
Replace代替
var ajaxURL = 'MMRController/TestAjax';
data: param = "this",
with和
var ajaxURL = '/MMR/TestAjax';
data: {param :"this"},
I would do 3 things differently:我会以不同的方式做三件事:
$.post
( https://api.jquery.com/jQuery.post/ )$.post
( https://api.jquery.com/jQuery.post/ )@Url.Action
( https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.urlhelper.action?view=aspnet-mvc-5.2 )@Url.Action
( https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.urlhelper.action?view=aspnet-mvc-5.2 ) Format your data as valid JSON将您的数据格式化为有效的 JSON
var url = '@Url.Action("TestAjax","MMR")';
// use this if you are using an MVC area // var url = '@Url.Action("TestAjax","MMRController", new { Area = "AreaNameGoesHere" })';
$.post(url, { param: 'this' }, function(){ // success callback }).fail(function(){ // failed callback });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.