如何使用 AJAX 正确调用 MVC 控制器



我正在尝试对我拥有的MVC控制器ActionResult进行AJAX调用。 我以前使用过ajax,但我是MVC的新手。 我在单独的.js文件中有一个 AJAX 调用,该调用在附加到视图中其中一个按钮的单击事件中触发。 AJAX 调用按预期触发,但始终返回"找不到资源"错误。 代码如下所示:

查看按钮:

<input type="button" class="btn btn-success" value="Download Pictures" id="btnGetPics"/>

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.");
}
});
});

控制器中的操作结果:

[HttpPost]
public ActionResult TextAjax(string param)
{
return Json(param + " works", JsonRequestBehavior.AllowGet);
}

以下是我收到的错误:

<!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. &nbsp;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>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3429.0
</font>
</body>
</html>
<!-- 
[HttpException]: A public action method &#39;MMRController&#39; was not found on controller &#39;MOHR.Controllers.MMRController&#39;.
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)
-->

任何帮助将不胜感激。

您没有正确设置data属性。

data: param = "this"

应该是

data: { param : "this"}, 

此外,您的网址需要在控制器(/(之前有一个正斜杠,并完全删除单词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.");
}
});

我会做3件不同的事情:

  • 使用简写 jQuery 帖子$.post(https://api.jquery.com/jQuery.post/(
  • 使用@Url.Action(https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.urlhelper.action?view=aspnet-mvc-5.2(
  • 将数据格式化为有效的 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 });

替换

var ajaxURL = 'MMRController/TestAjax';
data: param = "this",

var ajaxURL = '/MMR/TestAjax';
data: {param :"this"},

最新更新