开发者

Binding HttpPostedFileBase using Ajax.BeginForm

I have a form which binds a model and a file upload using the default binder for H开发者_如何学JAVAttpPostedFileBase.

This works fine when using Html.BeginForm(). However, I wanted to perform the same action using AJAX so I replaced this with Ajax.BeginForm() changing the parameters accordingly.

The model still binds correctly, however I can't get the file upload to bind to the HttpPostedFileBase.

This binds the model and the file upload:

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

This only binds the model:

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

The controller action:

public ActionResult MapUpdateColumns(DatasetViewModel model, HttpPostedFileBase sourceFile)

Should this be possible, and if so what am I doing wrong? Thanks.


You cannot upload files with AJAX. One way to achieve this is to use a hidden iframe which will simulate an AJAX call and perform the actual file upload or use Flash. Here's a very nice jQuery Form plugin using a hidden iframe which is capable of transparently ajaxifying a form submission containing file fields.


It is possible, the answer is here:

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

I did it myself and it's guaranteed it works.


ADD id="file" in your tag input

IN YOUR ACTIONRESULT PARAMETER HttpPostedFileBase 'file' name and view tag name should be same

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

IT WORKS FOR ME


Yes I also agree. You can definately upload files using 'Ajax.BeginForm'.Add 'enctype = "multipart/form-data"' to the AjaxOptions object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜