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??
First swapping parameters of your controller to have it as follows:
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: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.