我有一个 JS 函数:
$(document).on('click', '#submitForm', function (e) {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'bool',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
});
我的行动:
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 });
}
我在这里做错了什么?我正在尝试从 FileExist 方法获取 bool 值,如果为 true,则停止提交表单 (e.preventDefault)
最佳答案
没有数据类型:'bool'
。请使用 dataType:'json'
dataType:'text'
发送 bool 值
在你的情况下,它应该是dataType:'json'
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'json',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
然后
[HttpPost]
public ActionResult FileExist(string fileName)
{
}
关于javascript - 从 Controller 获取 Json 值到 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23606887/