0

I am working on a simple form where user will enter some data and select a file to upload. But i can not get this working.. For some reason when I click save, the file does not go to the controller.

Here is some code.

@using (Ajax.BeginForm("Add", "Category", null, new AjaxOptions
{
UpdateTargetId = "upload-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "uploadSuccess"
}, new { id = "AddCategoryForm", enctype = "multipart/form-data" }))
{
<div class="editorLabel">
    @Html.LabelFor(m=>m.CategoryName)
</div>
<div class="editorText">
    @Html.TextBoxFor(m=>m.CategoryName)
</div>
<div class="editorLabel">
    @Html.LabelFor(m => m.Description)
</div>
<div class="editorText">
    @Html.TextAreaFor(m => m.Description)
</div>

<div class="editorLabel">
    @Html.LabelFor(m => m.IconPath)
</div>
<div class="editorText">
    <input type="file" id="file" name="file" />
</div>
<div class="editorLabel">
    @Html.LabelFor(m => m.IsActive)
</div>
<div class="editorText">
    @Html.CheckBoxFor(m=>m.IsActive)
</div>
<p>
    <input type="submit" id="submit" value="Save" />
</p>

}

Controller:

[HttpPost]
    public ActionResult Add(HttpPostedFileBase file,CategoryViewModel model)
    {
        if (ModelState.IsValid)
        {
            System.IO.FileInfo info = new FileInfo(file.FileName);
            string ext = info.Extension;
            //other code
         }
      }

Here in the controller, file is always null. Where am I doing wrong??

Crime Master Gogo
  • 2,540
  • 10
  • 44
  • 75
  • 1
    Check [this](http://stackoverflow.com/questions/4856917/jquery-upload-progress-and-ajax-file-upload/4943774#4943774) answer about file upload using ajax. – Bojan Kaurin Sep 14 '12 at 23:07

1 Answers1

0

First swapping parameters of your controller to have it as follows:

[HttpPost]
public ActionResult Add(CategoryViewModel model, HttpPostedFileBase file)

For example.

If this won't work for some reason, make the file you uploading part of your model (CategoryViewModel) and have controller signature as follows:

[HttpPost]
public ActionResult Add(CategoryViewModel model)

For example. That way file will be returned as part of the model and you will extract it as one of model's properties. This will work (it worked for me).

Hope this helps.

Community
  • 1
  • 1
Display Name
  • 4,676
  • 1
  • 29
  • 43
  • Thanks. It worked when I made the image as the part of the viewmodel. But why it didn't work when i was sending the file as a separate parameter ? do you have any idea? – Crime Master Gogo Sep 16 '12 at 06:39
  • I think its because you swapped parameters, first comes model, second - `HttpPostedFileBase`. But cannot be sure, some things in ASP MVC are trial and error, rather than prior knowledge, at least in my case. The reason I knew the answer is because I did it myself before exactly as advised - include everything you need posted back in your viewmodel and you'll be OK. – Display Name Sep 16 '12 at 16:01