部署时无法找到控制器方法

时间:2014-05-14 09:04:05

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

控制器:

    [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中调试它时它工作正常。但是当我发布并将其放在服务器上时它就无法工作。

我的错误如下:

为什么发布时不起作用?

2 个答案:

答案 0 :(得分:2)

在视图中创建网址并设置javascript变量并在js文件中使用它。

用于cshtml文件

<script>
 var urlpath = '@Url.Action("FileExist","Calculation")';
</script>

用于js文件

$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
    type: 'POST',
    url: urlpath,
    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");
        }
    }
});
});

答案 1 :(得分:2)

考虑到Calculation是您的控制器类,请尝试按以下方式提供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文件中编写的,那么这里有一个代码。

在你的视图中将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");
        }
    }
});