简体   繁体   English

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

[英]How to pass a FormCollection and file to controller with AJAX JQuery ASP .NET MVC 4

I have a model class: 我有一个模型课:

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

I have a HTML form with inputs type text with Employee and Business data from Model and a input type file to load an image: 我有一个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>
}

I take the information from inputs with JQuery and pass to Controller with AJAX: 我使用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>
}

The controller: 控制器:

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

The question is: How to pass the image file too? 问题是:也如何传递图像文件?

Apparently the only solution is to pass the image converted in string encode to base 64: 显然,唯一的解决方案是将以字符串编码转换的图像传递给base 64:

HTML: 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>
}

SCRIPT: 脚本:

@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>
}

The controller: 控制器:

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

Please do this way, try to use FormCollection: 请这样做,尝试使用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>
}

And Change Action method according to this: 并据此更改Action方法:

[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("");
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Ajax和jQuery将复杂类型传递给ASP.NET MVC控制器 - How to Pass Complex Type to ASP.NET MVC Controller using Ajax and jQuery 如何通过Jquery.ajax()将字符串值从视图传递到ASP.NET MVC控制器 - How to pass string value from a view via Jquery.ajax() to ASP.NET MVC controller 控制器中带有 FormCollection 模型的 ASP.NET CORE MVC 发布表单 - ASP.NET CORE MVC post form with FormCollection Model in controller 没有在AJAX帖子中填充ASP.NET MVC 6 FormCollection - ASP.NET MVC 6 FormCollection not being populated in AJAX post 在Asp.net MVC中上传文件并通过FormCollection定位文件 - File Uploading in Asp.net MVC and geting the file through FormCollection 如何从FormCollection ASP.NET MVC分离值 - how to separate value from FormCollection ASP.NET MVC ASP.NET MVC通过AJAX调用将字符串传递给控制器 - ASP.NET MVC Pass a String to a Controller through an AJAX Call 如何在ASP.Net MVC中调用控制器方法并从Ajax调用传递对象 - How to call controller method and pass the object from ajax call in ASP.Net MVC ASP.Net Mvc 如何使用 Ajax 使用按钮将数据从视图传递到 Controller - ASP.Net Mvc How to pass data from View into Controller with a Button using Ajax 使用ASP.NET MVC显示FormCollection - Display FormCollection with ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM