首页 > 解决方案 > 如何将图像文件和表单数据从 Ajax 传递到 MVC 控制器

问题描述

我有一个带有图像和另一个文件的表单,我想在控制器中发送带有图像的数据。

  <form id="first-form"  method="post" enctype="multipart/form-data">
   <div class="row">
      <div class="col-md-9">
       <div class="row">
        <div class="col-sm-6 form-group">
         @Html.Label(@RegisterResource.Name, new { @class = "control-label" })
         <div class="field-input">
         @Html.TextBox("Name", null, new { placeholder = @RegisterResource.Name, autofocus = "autofocus", @class = "input-text" })
         @Html.ValidationMessage("Name", null, new { @class = "text-danger" })
        </div>
       </div>
      <div class="col-sm-6 form-group">
        @Html.Label(@RegisterResource.Family, new { @class = "control-label" })
         <div class="field-input">
         @Html.TextBox("Family", null, new { placeholder = @RegisterResource.Family, @class = "input-text" })
         @Html.ValidationMessage("Family", null, new { @class = "text-danger" })
        </div>
       </div>
       </div>
       <div class="row">
        <div class="col-sm-6 form-group">
          @Html.Label(@RegisterResource.CellPhone, new { @class = "control-label" })
           <div class="field-input">
           @Html.TextBox("CellPhone", null, new { placeholder = @RegisterResource.CellPhone, maxlength = 11, @class = "input-text", onkeydown = "return ValidateNumber(event);" })
            @Html.ValidationMessage("CellPhone", null, new { @class = "text-danger" })
           </div>
          </div>
          <div class="col-sm-6 form-group">
            @Html.Label(@ContractorResource.City, new { @class = "control-label" })
          <div class="field-input">
            @Html.DropDownList("CityId", (SelectList)ViewBag.City, new { placeholder = @ContractorResource.City, @class = "input-text" })
            @Html.ValidationMessage("CityId", null, new { @class = "text-danger" })
          </div>
         </div>
        </div>
        </div>
        <div class="col-md-3 text-center">
          <img id="image_upload_preview" class="img-circle" src="~/Content/Images/contractor-avator.png" />
          <br />
          <input type="file" id="inputFile" style="max-width: 200px" />
          <label for="inputFile" class="btn-2">انتخاب فایل تصویر</label>
         </div>
         </div>
         <div class="order-complate text-center">
         <button type="submit" class="awe-btn awe-btn-1 awe-btn-medium" id="user-register-btn" data-loading-text="<i class='fa fa-spinner fa-spin '></i> @PageResource.ConfirmCode">@PageResource.Continues</button>
         </div>
    </form>

在jQuery中

function readURL(input) {
 if (input.files && input.files[0]) {
   var reader = new FileReader();
   reader.onload = function(e) {
     $('#image_upload_preview').attr('src', e.target.result);
 }

 reader.readAsDataURL(input.files[0]);
 fileImage = input.files[0];
     }
}

$("#inputFile").change(function() {
  readURL(this);
});

submitHandler: function() {
  $("#user-register-btn").button('loading');
  var data = $('#first-form').serialize();
  var formData = new FormData();  
  formdata.append("img", fileImage );             
  $.post("/Contractor/SendConfirmCode",
   data,
    function(result) {
     } 
    else {
     }
   },
  "json");

但在控制器Request.Files中是Empty.

标签: jqueryajaxasp.net-mvcmodel-view-controllerasp.net-ajax

解决方案


感谢@jishan的全面回答;

如果我是你,我更喜欢发布表单数据的视图模型,但是,

根据您的看法:

    $('#user-register-btn').click(function (e) {

        e.preventDefault();

        $("#user-register-btn").button('loading');


        //var data = $('#first-form').serialize();
        var data = {
            Name: $('#Name').val(),
            Family: $('#Family').val(),
            CityId: $('#CityId').val(),
            CellPhone: $('#CellPhone').val()
        };

        var formData = new FormData();

        formData.append("data", JSON.stringify(data));

        var totalFiles = document.getElementById('inputFile').files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById('inputFile').files[i];
            formData.append("httpPostedFileBase", file);
        }
        $.ajax({
            type: "POST",
             url: '/Contractor/SendConfirmCode',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                if (response != null) {
                    console.log(response);      
                  $('#image_upload_preview').attr('src', response[0].FilePath);                 
                }
                else {
                    alert('No Response...!');
                }
            },
            error: function (error) {
                alert("error");
            }
        });
        
    });

在你的控制器中

    [HttpPost]
    public ActionResult SendConfirmCode(HttpPostedFileBase[] httpPostedFileBase, string data)
    {
        if(Request.Files.Count > 0)
        {
            // as you wish
        }


        ModelForm formData = JsonConvert.DeserializeObject<ModelForm>(data);
        // save formData to DB or ...

        return View();
    }

并且,与表单数据匹配的模型类

public class ModelForm
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string CityId { get; set; }
    public string CellPhone { get; set; }
}

推荐阅读