在bootstrap模式中使用时,MVC中的文件上载返回null

Kri*_*ota 8 asp.net-mvc file-upload httppostedfilebase twitter-bootstrap

我正在尝试将图像上传到我的应用程序,但它总是返回null.我在这里找不到问题.你能帮我吗?这是我的代码.

模型


[Table("Slider")]
public partial class Slider : BaseModel
{
    [Required]
    [StringLength(200)]
    public string FileName { get; set; }

    [StringLength(200)]
    public string Title { get; set; }

    [StringLength(1000)]
    public string Description { get; set; }

    public int? Order { get; set; }
}


[NotMapped]
public class SliderImage : Slider
{
    public HttpPostedFileBase ImageFile { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

视图


@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="modal-body">
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.FileName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.FileName, new { @class = "form-control", @readonly = "readonly" })
                @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.ImageFile, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.ImageFile, new { @class = "form-control", type = "file" })
               //This is Same as below
               //<input class="form-control" id="ImageFile" name="ImageFile" type="file" value="">
            </div>
        </div>
Run Code Online (Sandbox Code Playgroud)

调节器


    public ActionResult Edit(int id)
    {
        Slider slider = _db.Sliders.Find(id);
        if (slider == null)
        {
            return HttpNotFound();
        }
        Mapper.CreateMap<Slider, SliderImage>();
        SliderImage sliderImage = Mapper.Map<Slider, SliderImage>(slider);
        return PartialView("_Edit", sliderImage);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditSlider([Bind(Include = "Id,FileName,Title,Description,Order,IsActive,Name,ImageFile")] SliderImage sliderImage)
    {
        if (ModelState.IsValid)
        {
            Mapper.CreateMap<SliderImage, Slider>();
            Slider slider = Mapper.Map<SliderImage, Slider>(sliderImage);
            _db.Entry(slider).State = EntityState.Modified;
            _db.SaveChanges();
            return Json(new { success = true });
        }
        return PartialView("_EditSlider");
    }
Run Code Online (Sandbox Code Playgroud)

我这么做错了什么?


找到了问题

我绑定了bootstrap模式弹出窗口内的局部视图.当我从弹出窗口上传时,上传返回null.相反,如果我直接在浏览器中打开部分View,则该文件将出现在模型中.所以文件上传没有问题.问题是模态弹出或其他什么.

使用Bootstrap模型时 使用Bootstrap模型时

使用部分View Directy时 使用部分View Directy时

检查在下面的图像中分别使用引导程序模态提交和直接使用部分查看时使用fiddler时发现的差异

Fiddler请求的比较

从模态弹出窗口发布时,内容类型将更改为application/x-www-form-urlencoded直接使用局部视图时的内容类型multipart/form-data


找到了根本问题.

$('form', dialog).submit(function () {
                    var $form = $(this);
                    var enctype = $form.attr('id');
                    $.ajax({
                        url: this.action,
                        type: this.method,
                        data: $(this).serialize(),
                        success: function (result) {
                            if (result.success) {
                                $('#myModal').modal('hide');
                                //Refresh
                                location.reload();
                            } else {
                                $('#myModalContent').html(result);
                                bindForm();
                            }
                        }
                    });
                    return false;
                });
Run Code Online (Sandbox Code Playgroud)

我正在使用AJAX发布来提交表单中的数据.使用$(this).serialize()ajax时,正在调用成功但文件未返回,因为内容类型不同.我怎么能改变这个?

小智 0

尝试使用以下方法这对我有用:

看法 :

@using (Html.BeginForm("ComplaintAndSuggestion", "RegisterComplaints", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
:
:
:

                    <div class="row mb10">
                        <div class="col-sm-3 col-md-3">
                            <label for="file1">Upload Image 1</label>
                            <input type="file" name="images" id="file1" accept="image/*" />
                        </div>
                        <div class="col-sm-3 col-md-3">
                            <label for="file2">Upload Image 2</label>
                            <input type="file" name="images" id="file2" accept="image/*" />
                        </div>
                        <div class="col-sm-3 col-md-3">
                            <label for="file3">Upload Image 3</label>
                            <input type="file" name="images" id="file3" accept="image/*" />
                        </div>
                        <div class="col-sm-3 col-md-3">
                            <label for="file4">Upload Image 4</label>
                            <input type="file" name="images" id="file4" accept="image/*" />
                        </div>
                    </div>

   <input type="submit" value="Create" />

}
Run Code Online (Sandbox Code Playgroud)

控制器 :

     [HttpPost]
        public ActionResult ComplaintAndSuggestion(Register register, IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> videos)
        {


 foreach (var file in images)
                {

                    if (file != null)
                    {
                        string filenameWithDateTime = AppendTimeStamp(file.FileName);
                        file.SaveAs(Server.MapPath(Path.Combine("~/Images/", filenameWithDateTime)));
                        fileUploadModel.FilePath = (Server.MapPath(Path.Combine("~/Images/", filenameWithDateTime)));
                        fileUploadModel.FileName = filenameWithDateTime;
                        fileUploadModel.FileType = "Image";
                        fileUploadModel.RegisterId = register.RegisterId;
                        mediaRepository.Add(fileUploadModel);
                        mediaRepository.Save();
                    }

                }

}
Run Code Online (Sandbox Code Playgroud)

让我知道。