最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly call an MVC Controller with AJAX - Stack Overflow

programmeradmin2浏览0评论

I am trying to make an AJAX call to an MVC controller ActionResult that I have. I have used ajax before but I am new to 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. The AJAX call is being triggered as expected, but always returns with a "resource not found" error. Code shown below:

View Button:

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

AJAX Call:

    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:

        [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. &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& pletedSynchronously)
-->

Any help would be greatly appreciated.

I am trying to make an AJAX call to an MVC controller ActionResult that I have. I have used ajax before but I am new to 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. The AJAX call is being triggered as expected, but always returns with a "resource not found" error. Code shown below:

View Button:

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

AJAX Call:

    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:

        [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. &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& pletedSynchronously)
-->

Any help would be greatly appreciated.

Share Improve this question asked Dec 20, 2019 at 14:14 Marc RussoMarc Russo 351 silver badge5 bronze badges 7
  • use just var ajaxURL = 'TestAjax'; – sinitram Commented Dec 20, 2019 at 14:16
  • 1 The word "Controller" isn't part of the url even if it's part of the class, unless your class is named MMRControllerController. Try to access the url manually first. And the url should start with / if you specify the controller. – the_lotus Commented Dec 20, 2019 at 14:19
  • Try use url like this: var ajaxURL = '/MMR/TestAjax'; – nobody.price Commented Dec 20, 2019 at 14:21
  • @sinitram this results in a new error: Invalid JSON primitive: this. – Marc Russo Commented Dec 20, 2019 at 14:25
  • 1 @the_lotus After changing var ajaxURL = '/MMR/TestAjax' I am still getting "The resource cannot be found" as an error. More specifically that a public action method TestAjax was not found on controller MOHR.Controllers.MMRController. – Marc Russo Commented Dec 20, 2019 at 14:29
 |  Show 2 more ments

3 Answers 3

Reset to default 3

You aren't setting the data property correctly.

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...

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

I would do 3 things differently:

  • Use the shorthand jQuery post $.post (https://api.jquery./jQuery.post/)
  • Use @Url.Action (https://learn.microsoft./en-us/dotnet/api/system.web.mvc.urlhelper.action?view=aspnet-mvc-5.2)
  • Format your data as valid 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 });

Replace

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

with

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

评论列表(0)

  1. 暂无评论