简体   繁体   中英

JavaScript not firing in C# MVC4

I have the following code in my view :

    <script type="text/javascript">
    function OnCancelClick(e)
    {
        var jobId = e;
        var flag = confirm('You are about to cancel job : ' + jobId + '. Are you sure you want to cancel this job?');
        if (flag) {
            $.ajax({
                url: '/job/CancelJob',
                type: 'POST',
                data: { jobId: jobId },
                dataType: 'html',
                success: function (result) { alert('Job ' + jobId + ' was cancelled.'); document.location = "@Url.Action("Index", "Job")"; },
                error: function () { alert('Something went wrong. Check the log for more information.'); }
        });
    }
    return false;
    }
</script>

In my view I also have :

<input type="submit" id="cancelButton" value="Cancel" onclick="javascript: return OnCancelClick(@Model.Id);" />

In my controller I have :

[HttpPost]
        public ActionResult CancelJob(int jobId)
        {
            try
            {
                logger.LogInfo(string.Format("<start> Cancel-button clicked for job : {0}", jobId), jobId);

                JobCommandService.ChangeStatus(jobId, 6);

                logger.LogInfo(string.Format("<end> Cancel-button clicked for job : {0}", jobId), jobId);

                return RedirectToAction("Index", "Job");
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, ex, jobId);
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return Json(new { Success = false, Message = ex.Message });
            }
        }

When I run this in my VS2012 it works just fine. When I deploy it to the server, I'm getting the message that something went wrong. In my logging there is no trace of the button being clicked.

As per your comment, when deployed your app is installed in accindigoapps.blabla.lok/jobmonitor .

However your script has the url hardcoded as url: '/job/CancelJob' . That will mean:

  • when you are debugging from VS your script will work because the request is being sent to a url like http://localhost:XXX/job/CancelJob
  • however in production, the request will be sent to http://accindigoapps.blabla.lok/job/CancelJob , missing the jobmonitor part.

You need a way to inform your JS code about the base url of your application:

  • You could generate the Url in a Razor view using Url.Action("CancelJob","job") and pass that Url into your javascript code.

  • Another option would be to use Url.Content("~/") in some javascript of your base layout. That helper Url.Content("~/") will return only your application folder, / in your dev environment and /jobmonitor/ when deployed. That way you will have your app root-relative url available to any script, so you can use it to build root-relative urls as you were doing in your script:

     <script> var myApp = {}; myApp.BaseUrl = '@Url.Content("~/")'; </script> //Some other script like yours would be able to keep using root-relative urls as: $.ajax({ url: myApp.BaseUrl + 'job/CancelJob', ... 

If you prefer to generate full urls, you could follow a similar approach. Have a look at this question

Hope it helps!

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