在MVC 4中使用Ajax.BeginForm保存图像

Save Image Using Ajax.BeginForm in MVC 4
2020-11-21
  •  译文(汉语)
  •  原文(英语)

我正在尝试使用Ajax表单保存图像.但我无法获取上传的图片.这是我的索引页面,在此页面中,我正在加载AddItem的partialview.我的Index.Cshtml

@Html.Action("_AddOrUpdateItem","Admin")

我的动作代码

public PartialViewResult _AddOrUpdateItem(int? itemId)
        {
           //Some Code Here 
            return PartialView("_AddItem", item);
        }

        [HttpPost]
        public PartialViewResult AddOrUpdateItem(ToolItem toolItem, HttpPostedFileBase toolItemImage)
        {
           ////Some Code Here
            return PartialView("_AddItem", toolItem);
        }
    }

我的ajax形式如下

@using (Ajax.BeginForm("AddOrUpdateItem", "Admin", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
  // Some more text boxes here
  <input type="file" id="ToolItemImage" name="toolItemImage" />
  <input type="submit" value="Save" />
}

我有一个针对此类问题的链接,但就我而言,它不起作用

使用Ajax表单上传文件

速聊1:
什么不起作用?如果您调试该[HttpPost] AddOrUpdateItem() 方法,是否会影响您的操作?
速聊2:
是的,它正在执行我的操作,但是My toolItemImage为null.
速聊3:
您是否使用与所链接问题中相同的JavaScript代码?似乎很多类似的Ajax.BeginForm文件问题,而js是魔术棒.是否有不使用Html.BeginForm和覆盖自己的js提交的原因?IIRC您还应该将其视为集合,而不是链接的答案中的单个文件.
解决过程1

在链接中提供了没有附加js脚本的情况下,仅使用Ajax.BeginForm不可能加载文件,但是在您的代码中却看不到它.无论如何,我强烈建议您使用Jquery Form Plugin来实现此目的.

速聊1:
仅当我们想使用类似代码的形式提交表单时才需要form.js, $('#myForm').ajaxForm(function() { alert("Thank you for your comment!"); }); 但是在这里我要提交form.
解决过程2

我不知道ASP MVC,但是要提交带有文件的表格,您必须使用 enctype="multipart/form-data">

所以你的表格一定有这样的东西

<form action"your controller" method="post" enctype="multipart/form-data">
<input type="file" id="ToolItemImage" name="toolItemImage" />
<input type="submit">
</form>
解决过程3

保存Ajax.Begien表单图像保存此Jquery方法,并使用($("#frmUploader").valid())这行代码检查表单的有效性.

  @using (Ajax.BeginForm("Create", "Employee", new AjaxOptions()
        {
            OnBegin = "startBLoading",
            OnComplete = "stopBLoading",
            OnSuccess = "OnSuccessI"
        }, new { enctype = "multipart/form-data", id = "frmUploader" }))
        {
<div class=row>
..... Enter the Page View Desgine.....

<button type="submit" class="btn btn-product text-capitaliz">Create</button>
</div>
}
<script type="text/javascript">
 window.addEventListener("submit", function (e) {
        debugger

        if ($("#frmUploader").valid()) {
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    var xhr = new XMLHttpRequest();
                    xhr.open(form.method, form.action);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            if (form.dataset.ajaxUpdate) {
                                var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                                if (updateTarget) {
                                    updateTarget.innerHTML = xhr.responseText;
                                }
                            }
                        }
                    };
                    xhr.send(new FormData(form)

                    );

                }

            }
            OnSuccessI();
        } else {
            e.preventDefault();
        }
    },

        true
    );
</script>

I'm trying to Save Image Using Ajax form. But Unable to Get uploaded image in my action. This is my Index Page, In this page I'm loading partialview for Add Item . My Index.Cshtml

@Html.Action("_AddOrUpdateItem","Admin")

My Action Code

public PartialViewResult _AddOrUpdateItem(int? itemId)
        {
           //Some Code Here 
            return PartialView("_AddItem", item);
        }

        [HttpPost]
        public PartialViewResult AddOrUpdateItem(ToolItem toolItem, HttpPostedFileBase toolItemImage)
        {
           ////Some Code Here
            return PartialView("_AddItem", toolItem);
        }
    }

And My ajax form is as follow

@using (Ajax.BeginForm("AddOrUpdateItem", "Admin", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
  // Some more text boxes here
  <input type="file" id="ToolItemImage" name="toolItemImage" />
  <input type="submit" value="Save" />
}

I got a link for this same type of problem , But In my case it is not working

Upload file using Ajax form

Talk1:
What does not work? Does it hit your action if you debug the [HttpPost] AddOrUpdateItem() method?
Talk2:
Yes, It is hiting my action, but My toolItemImage is null.
Talk3:
Are you using the same javascript code as in the question you linked? Seems like a lot of similar problems with Ajax.BeginForm when it comes to files, and that the js is the magic wand. Any reason for not using Html.BeginForm and overriding submit with your own js? IIRC you should also treat it as a collection, rather than a single file, as in the answer you linked.
Solutions1

It's impossible load file using only Ajax.BeginForm without additional js script,which have been provided in your link and I can't see it in your code.Anyway I strongly recommend use Jquery Form Plugin for such purposes.

Talk1:
That form.js is need only when we want to submit form using code like $('#myForm').ajaxForm(function() { alert("Thank you for your comment!"); }); But here I I'm submitting form .
Solutions2

I dont know ASP MVC but for submitiing a form with file you have to use enctype="multipart/form-data">

so your form must be having something like this

<form action"your controller" method="post" enctype="multipart/form-data">
<input type="file" id="ToolItemImage" name="toolItemImage" />
<input type="submit">
</form>
Solutions3

Save Ajax.Begien Form Image save this Jquery method and also check validation your form using ($("#frmUploader").valid()) this line of code ...

  @using (Ajax.BeginForm("Create", "Employee", new AjaxOptions()
        {
            OnBegin = "startBLoading",
            OnComplete = "stopBLoading",
            OnSuccess = "OnSuccessI"
        }, new { enctype = "multipart/form-data", id = "frmUploader" }))
        {
<div class=row>
..... Enter the Page View Desgine.....

<button type="submit" class="btn btn-product text-capitaliz">Create</button>
</div>
}
<script type="text/javascript">
 window.addEventListener("submit", function (e) {
        debugger

        if ($("#frmUploader").valid()) {
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    var xhr = new XMLHttpRequest();
                    xhr.open(form.method, form.action);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            if (form.dataset.ajaxUpdate) {
                                var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                                if (updateTarget) {
                                    updateTarget.innerHTML = xhr.responseText;
                                }
                            }
                        }
                    };
                    xhr.send(new FormData(form)

                    );

                }

            }
            OnSuccessI();
        } else {
            e.preventDefault();
        }
    },

        true
    );
</script>
转载于:https://stackoverflow.com/questions/28397645/save-image-using-ajax-beginform-in-mvc-4

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入