ASP.NET MVC5 - 使用Ajax和FormData的文件上载表单始终为null

时间:2014-04-05 15:16:28

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

我的表格:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "userForm", enctype = "multipart/form-data"}))

{
    @Html.AntiForgeryToken()


        <div class="form-horizontal">
            <h4>Phone</h4>
            <hr />
            @Html.ValidationSummary(true)

                <div class="form-group">
                    @Html.LabelFor(model => model.Identification, new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Identification)
                        @Html.ValidationMessageFor(model => model.Identification)
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Location, new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Location)
                        @Html.ValidationMessageFor(model => model.Location)
                    </div>
                </div>

            <div class="form-group">
    @Html.LabelFor(model => model.AttachmentFile, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input type="file" name="AttachementFile" id="AttachementFile" />
        @Html.ValidationMessageFor(model => model.AttachmentFile)
    </div>
</div>
</div>
}

我的阿贾克斯:

 $(document).ready(function () {
        $('#button').on("click", function () {
            var selected = $('#HwType').val();
            var theData = $("#userForm").serialize();


            var form = $('form')[0];
            var formData = new FormData(form);

            $.ajax({
                type: "POST",
                url: selected + "/Create",
                data: formData,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response, status, xhr) {
                    $('#partialPlaceHolder').html('');
                    $('#messageHolder').html("Added to database");
                    $('#but').html('');
                    $('#HwType').val('choice');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $.each(jsonReponse, function (key, error) {

                        $('input[name="' + error.key + '"]').after(' ' + error.errors);

                    });

                    $('#messageHolder').html('Some fields were incorrect, please fix and resubmit');

                }
            })
        })

当我在传入的ViewModel的Controller的Action Create方法中放置断点时,HttpPostedFileBase文件始终为null。

我认为使用FormData会解决这个问题,但没有运气。我还尝试将文件输入放在我的表单之外并将其附加到FormData对象,但结果相同。

我做错了什么?

0 个答案:

没有答案