亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用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 關注
  • 139 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號