c# - 部署时找不到 Controller 方法

标签 c# javascript jquery ajax asp.net-mvc

Controller :

    [HttpPost]
    public ActionResult FileExist(string fileName)
    {
        bool result = true;
        string path = Server.MapPath(TempPath) + fileName + ".xlsx"; //Path for the file
        string[] Files = Directory.GetFiles(Server.MapPath(TempPath));
        for (int i = 0; i < Files.Length; i++)
        {
            if (path == Files[i])
            {
                //The filename already exists
                result = false;
            }
        }
        return Json(new { returnvalue = result });
    }

我的JS:

$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
    type: 'POST',
    url: '/Calculation/FileExist',
    data: { 'fileName': fileName },
    dataType: 'JSON',
    success: function (result) {
        if (!result.returnvalue) {
            $('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
            $('#downloadButton').css("visibility", "hidden");
        }
    }
});
});

当我在 VS 中调试它时,它工作正常。但是,当我发布并将其放在服务器上时,它就无法工作了。

我的错误是这样的:

为什么这在发布时不起作用?

最佳答案

考虑到 Calculation 是您的 Controller 类,尝试按以下方式给出 ajax 请求

$.ajax({
type: 'POST',
url: '@Url.Action("FileExist","Calculation")',,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
    if (!result.returnvalue) {
        $('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
            $('#downloadButton').css("visibility", "hidden");
        }
    }
});

如果这个事件是写在一个单独的 js 文件中,那么这里是一个代码。

在您的 View 中创建一个 js 函数作为

function GetUrlToCheckIfFileExist(){
    return '@Url.Action("FileExist","Calculation")';
}

在你的js文件中使用下面的代码

var getUrlToCheckIfFileExist = window.GetUrlToCheckIfFileExist();

$.ajax({
type: 'POST',
url: getUrlToCheckIfFileExist,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
    if (!result.returnvalue) {
        $('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
            $('#downloadButton').css("visibility", "hidden");
        }
    }
});

关于c# - 部署时找不到 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23650129/

相关文章:

c# - 在没有 APNS 的应用程序中显示 Apple 警报角标(Badge)

c# 字符串替换为关键字

javascript - 在 mvc JavaScript 中加载下拉更改选择的列

javascript - 使用 JavaScript 捕获浏览文件窗口的关闭

jquery - 如何使用 jQuery 重置选择元素

c# - 是否可以在 windows 窗体中使用 'sandbox' IE?

javascript - 如何使用 jQuery 设置/取消设置 cookie?

javascript - 无法读取 null 和覆盖的属性 'classList'

javascript - jquery 输入掩码用 asp.net 覆盖文本框值

jquery - 如何使用 jQuery 选择表格列