在引导模式使用时,MVC文件上传返回null [英] File upload in MVC when used in bootstrap modal returns null

查看:112
本文介绍了在引导模式使用时,MVC文件上传返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传图片到我的应用程序,但它总是返回null。我无法在这里找到问题。你能帮我吗?这里是我的code。

I'm trying to upload images to my application but it always returns null. I'm unable to find the issue here. Can you help me out? Here's my code.

型号

[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; }
}

查看

@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>

控制器

    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");
    }

我在做什么错了,我这个?

What am I doing wrong i this?

关于问题

我绑定的引导模式弹出内部的局部视图。当我从弹出的上传,上传返回null。相反,如果我直接在浏览器中打开局部视图,那么该文件是在模型$ P ​​$ psent。所以没有与文件上载没有问题。问题是与模式弹出什么的。

I'm binding the partial view inside the bootstrap modal popup. When I upload from the popup, the upload returning null. Instead if I open the partial View directly in browser, then the file is present in the model. So there is no problem with file upload. The problem is with modal popup or something.

通过引导模式时

When Using Bootstrap model

在使用局部视图Directy

When using partial View Directy

检查使用引导模态之间的小提琴手时提交和下面的图像分别直接使用局部视图中的区别

Check the difference found when using fiddler between the Bootstrap Modal Submit and Using the partial View Directly in the following image respectively

在从模式弹出发布,内容类型更改为应用程序/ x-WWW的形式urlen codeD ,其中直接使用的局部视图时,作为这是的multipart / form-data的

When posting from the modal popup, the content type is changed to application/x-www-form-urlencoded where as when using the partial view directly it is 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;
                });

我使用AJAX张贴从我的表单提交的数据。当使用 $(本).serialize()阿贾克斯成功被调用,但该文件没有返回的内容类型是不同的。我怎样才能改变这种??

I'm using AJAX posting to submit the data from my form. When using $(this).serialize() the ajax success is being called but the file is not returning as the content type is different. How can I change this??

推荐答案

好吧,我想你目前的问题涉及到了jQuery.ajax方法的默认设置。默认情况下,内容类型为jQuery.ajax()方法是应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8。因此,在一个示例项目,我修改你的JavaScript函数指定的contentType作为一个参数设置为给AJAX方法:的contentType:this.enctype

Ok, I think your current issue is related to the default settings for the jQuery.ajax method. By default, the content type for the jQuery.ajax() method is 'application/x-www-form-urlencoded; charset=UTF-8'. So, in a sample project, I modified your javascript function to specify the contentType as a paramter to the ajax method: contentType: this.enctype

我想可能也有一对夫妇的其他问题。我注意到的下一个问题是,在提交,我被连接到另一个动作,所以我更新了针对这一行:

I think there also may be a couple additional issues. The next issue that I noticed is that on submission, I was connecting to another actions, so I updated this line in the view:

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

要这样:

@using (Html.BeginForm("EditSlider", "<Your Controller Name>", FormMethod.Post, new { enctype = "multipart/form-data" }))

最后,AJAX提交的时候,我被重定向到局部视图。我相信这可以通过增加preventDefault的AJAX功能是固定的:

Lastly, when the ajax submitted, I was being redirected to the partial view. I believe this can be fixed by adding preventDefault to the ajax function:

$('form', dialog).submit(function (event) {
    event.preventDefault();
    var $form = $(this);
    $.ajax({
        url: this.action,
        type: this.method,
        contentType: this.enctype,
        data: $(this).serialize(),
        success: function (result) {
            if (result.success) {
                $('#myModal').modal('hide');
                //Refresh
                location.reload();
            } else {
                $('#myModalContent').html(result);
                bindForm();
            }
        }
    });
});

这是我如何能得到这个例子中的一个样本项目工作;如果您还有其他问题,请发布更新。

This is how I was able to get this example working in a sample project; please post an update if you have additional issues.

这篇关于在引导模式使用时,MVC文件上传返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆