如何使用AJAX JQuery ASP .NET MVC 4将FormCollection和文件传递给控制器

时间:2019-02-03 01:30:27

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

我有一个模型课:

public class Register
{
    public Employee Employee { get; set; }
    public Business Business { get; set; }
}

我有一个HTML表单,其中包含输入类型的文本和来自Model的Employee和Business数据,以及一个输入类型的文件以加载图像:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "frmRegister", @enctype = "multipart/form-data" }))
{
   @Html.AntiForgeryToken()
   <div class="div-file">
      <input id="inputFile" title="Upload a business image" type="file" name="UploadedFile" accept="image/*" />
   </div>
   <div class="div-input">
     @Html.Label("Name:", htmlAttributes: new { @for = "txtName" })
     @Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
   </div>
   <div class="div-input">
     @Html.Label("Age:", htmlAttributes: new { @for = "txtAge" })
     @Html.EditorFor(model => model.Employee.Age, new { htmlAttributes = new { @class = "form-control", @id = "txtAge" } })
   </div>
   <div class="div-input">
      @Html.Label("Company:", htmlAttributes: new { @for = "txtCompany" })
      @Html.EditorFor(model => model.Business.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
  </div>
  <div class="div-input">
       @Html.Label("Phone:", htmlAttributes: new { @for = "txtPhone" })
       @Html.EditorFor(model => model.Business.Phone, new { htmlAttributes = new { @class = "form-control", @id = "txtPhone" } })
  </div>
  <div class="text-center">
     <input type="button" id="btnRegister" value="Register" class="btn btn-default" />
   </div>
}

我使用JQuery从输入中获取信息,然后使用AJAX传递给Controller:

@section Scripts {
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#btnRegister").on('click', function (e) {
                e.preventDefault();
                var image = document.getElementById("inputFile").files[0];
                var frmRegister = $("#frmRegister").serialize();
                 $.ajax({
                    url: '@Url.Action("Create", "Register")',
                    type: 'POST',
                     traditional: true,
                     data: frmRegister,
                     dataType: 'json',
                     ContentType: "application/json;utf-8",
                     cache: false,
                     success: function (response) {

                     },
                      error: function (response) {
                         alert(response.responseText);
                     }
                });
            });
        });
    </script>
}

控制器:

public ActionResult Create(FormCollection collection)
      {
            //HttpPostedFileBase file = Request.Files["UploadedFile"];
            return View();
      }

问题是:如何也传递图像文件?

2 个答案:

答案 0 :(得分:1)

显然,唯一的解决方案是将以字符串编码形式转换的图像传递给base 64:

HTML:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "frmRegister", @enctype = "multipart/form-data" }))
{
   @Html.AntiForgeryToken()
   <div class="div-file">
      <input id="inputFile" title="Upload a business image" type="file" name="UploadedFile" accept="image/*" onchange="encodeImagetoBase64(this)"/>
   </div>
    <div>
        <p id="pImageBase64"></p>
    </div>
    <div>
        <img id="image" height="150">
    </div>
   <div class="div-input">
     @Html.Label("Name:", htmlAttributes: new { @for = "txtName" })
     @Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
   </div>
   <div class="div-input">
     @Html.Label("Age:", htmlAttributes: new { @for = "txtAge" })
     @Html.EditorFor(model => model.Employee.Age, new { htmlAttributes = new { @class = "form-control", @id = "txtAge" } })
   </div>
   <div class="div-input">
      @Html.Label("Company:", htmlAttributes: new { @for = "txtCompany" })
      @Html.EditorFor(model => model.Business.Name, new { htmlAttributes = new { @class = "form-control", @id = "txtName" } })
  </div>
  <div class="div-input">
       @Html.Label("Phone:", htmlAttributes: new { @for = "txtPhone" })
       @Html.EditorFor(model => model.Business.Phone, new { htmlAttributes = new { @class = "form-control", @id = "txtPhone" } })
  </div>
  <div class="text-center">
     <input type="button" id="btnRegister" value="Register" class="btn btn-default" />
   </div>
}

脚本:

@section Scripts {
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#btnRegister").on('click', function (e) {
                e.preventDefault();
                var imagenBase64 = $("#pImageBase64").html();
                var name = $("#txtName").val();
                var age= $("#txtAge").val();
                var params = {
                    file: imagenBase64,
                    name: name,
                    age: age
                }
                 $.ajax({
                    url: '@Url.Action("Create", "Register")',
                    type: 'POST',
                     traditional: true,
                     data: params,
                     dataType: 'json',
                     ContentType: "application/json;utf-8",
                     cache: false,
                     success: function (response) {

                     },
                      error: function (response) {
                         alert(response.responseText);
                     }
                });
            });
        });
        function encodeImagetoBase64(element) {
            var file = element.files[0];
            var reader = new FileReader();
            reader.onloadend = function () {
                $("#image").attr("src", reader.result);
                $("#pImageBase64").html(reader.result);

            }
            reader.readAsDataURL(file);
        }
    </script>
}

控制器:

public ActionResult Create(string file, string name, string age)
{
  return Json("success!!!");
}

答案 1 :(得分:0)

请这样做,尝试使用FormCollection:

@section Scripts {
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#btnRegister").on('click', function (e) {
                e.preventDefault();
                var image = document.getElementById("inputFile").files[0];
                var frmRegister = $("#frmRegister").serialize();

                var formData = new FormData();
                formData.append("imageFile", image );
                formData.append("RegisterData", frmRegister);
                 $.ajax({
                    url: '@Url.Action("Create", "Register")',
                    type: 'POST',
                     traditional: true,
                     data: formData,
                     processData: false,
                     dataType: 'json',
                     ContentType: false,
                     cache: false,
                     success: function (response) {

                     },
                      error: function (response) {
                         alert(response.responseText);
                     }
                });
            });
        });
    </script>
}

并根据此更改操作方法:

[HttpPost]
        public ActionResult Create()
        {
            string serializedRegisterData = Request["RegisterData"]; //you can do code of deserialization for form data.

            var image= Request.Files[0];
            var imagePath = Path.GetFileName(image.FileName);

            return Json("");
        }