简体   繁体   中英

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. 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& completedSynchronously)
-->

Any help would be greatly appreciated.

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

Replace

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

with

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

I would do 3 things differently:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM