使用Ajax.BeginForm绑定HttpPostedFileBase

时间:2010-03-22 10:00:40

标签: asp.net-mvc ajax model-binding

我有一个表单,它使用HttpPostedFileBase的默认绑定器绑定模型和文件上载。

使用Html.BeginForm()时这很好用。但是,我想使用AJAX执行相同的操作,所以我将其替换为Ajax.BeginForm(),相应地更改了参数。

模型仍然正确绑定,但是我无法将文件上传到HttpPostedFileBase。

这会绑定模型和文件上传:

<% using (Html.BeginForm("MapUpdateColumns", "RepositoryAdmin", FormMethod.Post, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>

这只会绑定模型:

<% using (Ajax.BeginForm("MapUpdateColumns", "RepositoryAdmin", new AjaxOptions { UpdateTargetId = "columnMappings" }, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>

控制器操作:

public ActionResult MapUpdateColumns(DatasetViewModel model, HttpPostedFileBase sourceFile)

这是否可能,如果是这样,我做错了什么?感谢。

4 个答案:

答案 0 :(得分:9)

您无法使用AJAX上传文件。实现此目的的一种方法是使用隐藏的iframe,它将模拟AJAX调用并执行实际的文件上载或使用Flash。这是一个非常好的jQuery Form插件,它使用隐藏的iframe,它能够透明地提示包含文件字段的表单提交。

答案 1 :(得分:2)

有可能,答案就在这里:

https://stackoverflow.com/a/13522052/1067149

我自己做了,但保证它有效。

答案 2 :(得分:0)

在标记输入中添加id="file"

在你的行动结果参数中 HttpPostedFileBase'文件'名称和视图标记名称应相同

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(tbl_products tbl_products,HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                tbl_products.phototype = file.ContentType;
                tbl_products.photo =new byte[file.ContentLength ];
                file.InputStream.Read(tbl_products.photo,0, file.ContentLength);

                if(obj.insert(tbl_products))
                {
                return RedirectToAction("Index");
                }
                else
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
                }   
            }

            return View(tbl_products);
        }

为我工作

答案 3 :(得分:-1)

是的,我也同意。你可以使用&#39; Ajax.BeginForm&#39; .Add&#39; enctype =&#34; multipart / form-data&#34;&#39;来定义上传文件。到AjaxOptions对象。

相关问题