javascript - 从 Controller 获取 Json 值到 jquery

标签 javascript jquery ajax asp.net-mvc

我有一个 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/

相关文章:

javascript - ionic 如何转换和重新加载页面

javascript - 将输入值设为数组

javascript - 用于样式和事件的 CSS 类的命名约定是什么?

javascript - js文件中的eex语法或Phoenix代码

javascript - 平滑更改内联 block 容器高度

jquery - 如何在日期选择器中设置 3 个月的日期范围?

javascript - AngularJS:当 php 返回 JSON 字符串时,为什么 $http response.data 是一个对象?

javascript - 如何让 forEach 循环等待每个 Ajax 函数完成

javascript - 对于 Ajax 请求,我的函数应该通过 .fail() 回调返回什么?

JavaScript 数组迭代器