为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用AJAX JQuery ASP .NET MVC 4将表单集合和文件传递到控制器

如何使用AJAX JQuery ASP .NET MVC 4将表单集合和文件传递到控制器

C#
料青山看我应如是 2022-08-20 17:28:04
我有一个模型类:public class Register{    public Employee Employee { get; set; }    public Business Business { get; set; }}我有一个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/*" />   </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>}问题是:如何传递图像文件?
查看完整描述

2 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

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


网页:


@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!!!");

}


查看完整回答
反对 回复 2022-08-20
?
qq_遁去的一_1

TA贡献1725条经验 获得超8个赞

请这样做,尝试使用表单集合:


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

        }


查看完整回答
反对 回复 2022-08-20
  • 2 回答
  • 0 关注
  • 157 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号