0

I want to upload image using Ajax.BeginForm in my application.

Currently HttpPostedFileBase file is getting value 0. Anyone Please guide me here.

I have tried this code but file is not uploading.

Appreciated, if anyone can provide some solutions for this. If I use @Html.BeginForm then It works but I want to use @Ajax.BeginForm.

Model

 public class ClsUpload
    {
        public string FilePath { get; set; }
    }

Controller

public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
        {
            if (Request.Files.Count > 0)
            {
                 file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(file.FileName);
                    string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
                    file.SaveAs(path);
                    model.FilePath = path;
                }   
            }

            try
            {
                UploadDetials details = new UploadDetials();

                 details.UpdateDetails(model);
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }

        }

Partial View

 @model XX.X.Models.File.ClsUpload

 @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
    { 
    @Html.HiddenFor(model => model.FilePath)
       <input type="file" name="file" />
      <img src=@Model.FilePath alt="Image" />

      <input type="submit" value="Save" />
    }   
MVC
  • 649
  • 7
  • 23
  • Instead of an Ajax.BeginForm, could you not use a Html.BeginForm? – JamesS Jul 09 '18 at 14:08
  • Why do you want to use Ajax.Begin form? I've recently read some articles that say its becoming obsolete. – Wheels73 Jul 09 '18 at 14:31
  • @JamesS, No. I do not want to use Html.BeginForm. If there is anyway to do with Ajax.BeginForm then please share some ideas. – MVC Jul 09 '18 at 20:31
  • @Wheels73, The form is setup in such a way that I can only use Ajax.BeginForm. Please suggest some Ideas. – MVC Jul 09 '18 at 20:32
  • You cannot use `Ajax.BeginForm()` to upload files. Use `$.ajax()` and `FormData` and set the correct options - refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for an example –  Jul 09 '18 at 22:09
  • @StephenMuecke, can you please suggest me in my case. If possible then can you please answer this. Highly appreciate your time. – MVC Jul 09 '18 at 22:25
  • @StephenMuecke, Can you please provide me an answer for this. I am struggling since morning. – MVC Jul 09 '18 at 22:38
  • @MVC, Did you read through the link I gave you - it explains how to do it –  Jul 09 '18 at 23:17

2 Answers2

0

You can update your code with FormMethod.Post, new { enctype = "multipart/form-data" }) and [AcceptVerbs(HttpVerbs.Post)] as follow

In Partial View

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

}

In Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}
Dip Surani
  • 61
  • 6
0

This is old, but I want to show how I have accomplished uploading a file using Ajax.BeginForm(). Basically, the overloads will tell you what is possible. I use the overload for: "string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes". Note: I use null for "routeValues".

Here is a code example:

@using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", @id = "NewFileFormID" }))
    {
        @Html.AntiForgeryToken()
        <div class="row">
            <div class="col-sm-8 col-sm-offset-1">
                @Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", @id = fileID, onchange = VerifySizeOfFile })
            </div>
            <div class="col-sm-2">
                 <button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
            </div>
        </div>
    }
C4A
  • 1
  • 1