Skip to main content
 首页 » 编程设计

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

2024年02月13日9cloudgamer

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