如何显示json错误消息



我无法显示Json消息,我试图阻止用户上传同名文件,这是我的控制器代码:

     //POST: /Quote/Create   Save the Uploaded file
    public ActionResult SaveUploadedFile(int? chunk, string name)
    {
        bool exists;
        var fileUpload = Request.Files[0];
        var uploadPath = "C:\Files";        
        chunk = chunk ?? 0;
        if (System.IO.File.Exists(Path.Combine(uploadPath, name)))
        {
            exists = true;
        }
        else {
            exists = false;
        }
        if (!exists)
        {
            using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                var buffer = new byte[fileUpload.InputStream.Length];
                fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
            }
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }
        else {
            return Json(new { success = false, Message = "The file" + name +"already exists" }, JsonRequestBehavior.AllowGet);
        }
    }

这是我的视图代码,如果files success为false,则显示Json消息:

            UploadComplete: function (up, files) {
            if (!files.success) {
                alert(files.Message);
                console.log(up);
            } else {
                var j = 0;
                if (count > 0) {
                    j = count;
                } else {
                    j = @i + '';
                }
                $.each(files, function (i, file) {
                    var extension = file.name.split(".");
                    $('.files').append('<input type="hidden" name="Files[' + j + '].Name" value="' + file.name + '" />');
                    $('.files').append('<input type="hidden" name="Files[' + j + '].Date" value="' + "@DateTime.Now" + '" />');
                    j++;
                });
            }
        }

提前感谢!!

似乎您需要返回字符串结果而不是ActionResult,因为您真正想要的是它是否通过。还可以稍微缩短代码以反映更改。

如果你确实想返回一个对象(意味着你想要多个属性),我会创建一个模型(类和对象),然后返回JsonResult而不是ActionResult

关于如何返回JsonResult对象的良好文档

c#

public string SaveUploadedFile(int? chunk, string name)
{
    bool exists = false;
    var fileUpload = Request.Files[0];
    var uploadPath = "C:\Files";        
    chunk = chunk ?? 0;
    exists = System.IO.File.Exists(Path.Combine(uploadPath, name));
    if (!exists)
    {
        using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
        {
            var buffer = new byte[fileUpload.InputStream.Length];
            fileUpload.InputStream.Read(buffer, 0, buffer.Length);
            fs.Write(buffer, 0, buffer.Length);
        }
     }
     return message = !exists ? string.Empty
                              : "The file" + name + " already exists";
} 
Javascript

if (files.message != '') {   // meaning "exists" is true
     console.log(up);
} else {
     ......
     ......
}

相关内容

  • 没有找到相关文章

最新更新