如何通过ASP.NET MVC中的Ajax JSON一起发送数据和图像 [英] How to send data and image together through ajax json in asp.net mvc

查看:82
本文介绍了如何通过ASP.NET MVC中的Ajax JSON一起发送数据和图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我只需要创建一个仅包含要发送到操作而不是图像的数据的表单,现在,我面临着将数据与图像一起发布到操作的要求.我不知道如何将图像添加到数据中,这样我就可以继续工作.

Previously, I just had a requirement to create a form that contains only data to be sent to the action and not the image, now, I've confronted with a requirement to POST the data along with an image to the action. I've no idea how to append the image to the data so that I can get it work to proceed further in action.

这是我将数据和图像一起发布的方式,但实际上我收到null:

This is how I'm posting the data and the image together but I receive null in action :

HTML

<input type="file" id="profilePic" name="file" value="Browse">
<input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
<input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
<input type="button" value="Create" onclick="SaveEmpData()" />

我知道如何获取输入类型的文本数据并通过ajax请求以json格式发送并将其保存到数据库中,但是当涉及到通过json格式通过ajax请求获取数据和图像时,我关于如何做到这一点一无所知.

I know how to get the input type text data and send it through ajax request and in a json format and save it to database, but when it comes to get the data and image through the ajax request in a json format, I've got no clue about how to do this.

JS

var empdata = { "SystemCode": "", "EmployeeCode": "" };

empdata.EmployeeCode = $("#EmployeeCode").val();
empdata.SystemCode = $("#SystemCode").val();

var data = new FormData();
var files = $("#profilePic").get(0).files;    
data.append("Image", files[0]); 

Ajax

$.ajax({
    url: '/EmployeeMasterA/Create',
    headers: headers,
    data: JSON.stringify({ employeeMasterA: empdata, profilePic: data }),
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    traditional: true,
    success: function (result) {

        if (result.Success == "1") {
            window.location.href = "/EmployeeMasterA/Index";
        }
        else {
            alert(result.ex);
        }
    }
});

Create操作:

[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA, HttpPostedFileBase profilePic)
{            
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

在上面的代码中,pic变量是null.我的问题是:

In the above code, the pic variable is null. My question is:

从表单获取数据和图像并将其通过ajax请求发送到操作的正确方法是什么?任何帮助深表感谢:)

What is the proper way to get the data + image from the form, and send it through the ajax request to the action? Any help is deeply appreciated :)

更新

参考liran的回答后,我尝试通过以下方式编辑代码来进行绑定:

After referring to liran's answer, I tried binding by editing my code this way :

JS

var empbind = { "profilePic" : "", "employeeMasterA" : "" };
// Created empdata and data (image) object as mentioned above
empbind.employeeMasterA = empdata;
empbind.profilePic = data;
var empbindjson = JSON.stringify(empbind);

并如下更改 Ajax data参数:

$.ajax({
   .
   .
   data: empbindjson,
   .
   .
});

并更改了我的控制器操作:

And Changed my controller action :

[HttpPost]
public ActionResult Create([Bind(Include = "employeeMasterA,profilePic")]       EmployeeBind bind)
{            
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

在上述代码的调试模式下,两个employeeMasterA,profilePic都被null接收,这是我绑定的新类:

Both employeeMasterA,profilePic are received null in debug mode of the above code, this is my new class for binding :

public class EmployeeBind
{
    public EmployeeMasterA employeeMasterA { get; set; }
    public HttpPostedFileBase profilePic { get; set; }
}

好,现在,我已更改代码以将其与profilePic绑定,我做错了什么吗?因为创建action的两个bind参数都为employeeMasterA和profilePic都包含空值.

Ok, Now, I've changed my code to bind it with the profilePic, Is there any thing I doing wrong? because both bind parameter of the create action contains null for both employeeMasterA and profilePic.

推荐答案

尝试更改需要工作的内容:

Try change something like that need to work:

  $('#save').click(function () {

    var form = $("#yourForm");
    var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("Image", files[0]);
    $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

  $.ajax({
      url: '/EmployeeMasterA/Create',
      data: data,
      type: 'POST',
      processData: false,
      contentType: false,
      success: function (result) {

          if (result.Success == "1") {
              window.location.href = "/EmployeeMasterA/Index";
          }
          else {
              alert(result.ex);
          }
      }
  });
});

在HTML中:

 <form id="yourForm">
    <input type="file" id="profilePic" name="file" value="Browse">
    <input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
    <input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
    <input type="button" value="Create" onclick="SaveEmpData()" id="save">
</form>

如果仍然无法正常工作,则将EmployeeMasterA和HttpPostedFileBase绑定到同一类,例如:

if that still not working so bind the EmployeeMasterA and HttpPostedFileBase to same class something like :

    [HttpPost]
    public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] VMNewClass bind)
    {            
        var pic = System.Web.HttpContext.Current.Request.Files["Image"];
    }


public class VMNewClass{

 public EmployeeMasterA employeeMasterA {get;set;}
 public  HttpPostedFileBase profilePic {get;set;}

}

如果您不想这样做:

 $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

您可以写:

var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("profilePic", files[0]);
    data.append("EmployeeCode", $("#EmployeeCode").val());
    data.append("SystemCode", $("#SystemCode").val());

编辑我是否在评论中附加了文章

 <script>
        var empdata = { "SystemCode": "", "EmployeeCode": "" };

        empdata.EmployeeCode = $("#EmployeeCode").val();
        empdata.SystemCode = $("#SystemCode").val();

        var data = new FormData();
        var files = $("#profilePic").get(0).files;
        data.append("Image", files[0]);
        data.append("EmployeeCode", $("#EmployeeCode").val());
        data.append("SystemCode", $("#SystemCode").val());

        $.ajax({
            url: '/EmployeeMasterA/Create',
            data: data,
            type: 'POST',
            contentType: false, // Not to set any content header  
            processData: false, // Not to process data  
            success: function (result) {

                if (result.Success == "1") {
                }
                else {
                    alert(result.ex);
                }
            }
        });

</script>

控制器:

[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA)
{            
    HttpPostedFileBase profilePic = Request.Files[0]; // your file
}

这篇关于如何通过ASP.NET MVC中的Ajax JSON一起发送数据和图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆