控制器:
[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中调试它时它工作正常。但是当我发布并将其放在服务器上时它就无法工作。
我的错误如下:
为什么发布时不起作用?
答案 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");
}
}
});