【问题标题】:upload file in jquery ajax to asp.net, but result json fail将jquery ajax中的文件上传到asp.net,但结果json失败
【发布时间】:2016-03-17 03:04:31
【问题描述】:

我的步骤: 第1步。上传文件到服务器 第2步。服务器获取文件并将其保存到存储中 第三步。服务器将结果(成功或失败)返回给客户端

Step3中的程序错误, 文本状态 = 解析器错误; 就绪状态:4

在客户端:

var data = new FormData();
data.append("file", document.getElementById('file').files[0]);
data.append("id",$('#saveClassID').val());                

$.ajax(
       {
           url: uploadFile,
           data: data,  //
           type: 'post',
           async: false,    
           contentType: false,               
           dataType: 'json',
           processData: false,
           success: function (data) {                   
               if (data.status == "OK") {                      
                   alert('success');
               }
               else {
                   alert(fail);
               }
           },
           error: function(jqXHR, textStatus, errorThrown) {
               console.log(textStatus, errorThrown);
           }
       });

在服务器端:

[HttpPost]
    public ActionResult uploadFile()
    {
        HttpPostedFileBase file = (HttpPostedFileBase)Request.Files["file"];
        int save_id = Convert.ToInt32(Request.Form["id"].ToString());

        Result result = new Result();
        if (file != null)
        {
            if (file.ContentLength > 0)
            {
              //savedata, and get result  public Result saveData(file,id)
                  result = saveData(file,id);           
            }
            else
            {
                    result.msg="error";
                    result.staut="fail";
            }
        else
        {
             result.msg="no file";
            result.status="fail";
        }
        return Json(result, JsonRequestBehavior.AllowGet);

   }

   public class Result
   {
        public string status;
        public string msg;         
   }

我不知道如何修改我的代码, 1.如果我在客户端修改代码,“contentType:false”为json, 服务器端将无法获得“ID”, 2.如果我在服务器端修改代码进行测试, “返回 Json (返回 Json(new{status = "OK"}, JsonRequestBehavior.AllowGet);" ,代码还是失败了

谢谢

【问题讨论】:

  • 您需要先创建Result 属性,而不是字段(使用{ get; set; }
  • 除非你在某处定义了一个变量,否则它的alert('fail');(引号)
  • 将您的成员变量作为属性示例:public string Status { get; set; }

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


【解决方案1】:

试试

return Json(new {result}, JsonRequestBehavior.AllowGet); 

添加 Result 属性后,而不是 @Stephen Muecke 提到的字段(带有 { get; set; })

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 2012-03-06
    • 2015-08-25
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多