【问题标题】:Submitting form with photo data using ajax and mvc使用 ajax 和 mvc 提交带有照片数据的表单
【发布时间】:2018-06-30 10:06:43
【问题描述】:

我正在尝试使用 ajax 提交我的表单,因为当我提交表单时页面重新加载的典型方式并且我忘记了选择了哪些单选按钮。

我尝试了几种方法,但这个方法似乎是最有希望的。当我使用 JQuery 抓取元素时,我从表单中序列化数据,然后向我的控制器发送一个帖子,但是当我使用此方法时,我上传的 ImageFile 总是返回 null,任何帮助将不胜感激!

照片类:

namespace MVCEventCalendar
{
    using System;
    using System.Collections.Generic;

    public partial class Photo
    {
        public string Path { get; set; }
        public string SubEvent { get; set; }
        public int EventID { get; set; }
        public int ID { get; set; }

        public System.Web.HttpPostedFileBase ImageFile { get; set; }
    }
}

控制器:

[HttpPost]
public JsonResult AddInspectionPhoto(Photo imagemodel)
{
    string fileName = Path.GetFileNameWithoutExtension(imagemodel.ImageFile.FileName);
    string extension = Path.GetExtension(imagemodel.ImageFile.FileName);
    fileName = fileName + "_" + imagemodel.EventID + "_" + imagemodel.SubEvent;
    imagemodel.Path = "../InspectionPhotos/" + fileName + "." +extension;
    fileName = Path.Combine(Server.MapPath("../InspectionPhotos/"), fileName + extension);
    imagemodel.ImageFile.SaveAs(fileName);

    using (InspectionPhotoEntities db = new InspectionPhotoEntities())
    {
        imagemodel.EventID = Convert.ToInt32(Session["Event"].ToString());
        imagemodel.SubEvent = "GC1";
        db.Photos.Add(imagemodel);
        db.SaveChanges();
    }
    //ModelState.Clear();
    var status = true;
    return new JsonResult { Data = new { status = status } };
    //return View("~/Views/Home/InspectionChecklist.cshtml");
}

HTML:

   <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"><span id="eventTitle">Upload a Photo!</span></h4>
                </div>
                <div class="modal-body">

                    <form asp-controller="Home" asp-action="AddInspectionPhoto" method="post" id="photoform" role="form">

                            <div class="form-group">
                                <div class="col-sm-12" style="text-align:center;">
                                    <input type="file" name="ImageFile" id="imageFile" />
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-12" style="text-align:center;">
                                    <button type="button" style="background-color: #454545; color: #ffffff;" class="btn btn-default" id="submitPhoto">Submit Photo</button>
                                </div>
                            </div>

                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

JQuery:

        $('body').on('click', '#submitPhoto', function () {

            //var filePath = $('#imageFile').filePath;

            //var imageJSON = {
            //    SubEvent: SubEvent,
            //    ImageFile: filePath
            //}


            //UploadPhoto(imageJSON);
            console.log("submittingform");
                var $form = $('photoform');

                $.ajax({
                    type: "POST",
                    url: '/home/AddInspectionPhoto',
                    data: $form.serialize(),
                    error: function (xhr, status, error) {
                        //do something about the error
                    },
                    success: function (response) {
                        //do something with response
                        //LoadBooks();
                        console.log("DONEEEE");
                    }
                });

                return false;// if it's a link to prevent post



        });

这里一定有什么我遗漏的东西,可能是序列化数据或我发送照片的方式吗?

【问题讨论】:

    标签: jquery ajax asp.net-mvc forms


    【解决方案1】:

    serialize() 不适用于文件输入,您需要使用 FormData 对象并阻止 jQuery.ajax 设置内容类型和处理您传递的数据

                $.ajax({
                    type: "POST",
                    url: '/home/AddInspectionPhoto',
                    data: new FormData($form[0]),
                    contentType: false,
                    processData: false,
                    error: function (xhr, status, error) {
                        //do something about the error
                    },
                    success: function (response) {
                        //do something with response
                        //LoadBooks();
                        console.log("DONEEEE");
                    }
                });
    

    【讨论】:

    • 现在试试看:D
    猜你喜欢
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多