I'm working on an app on ASP.Net MVC 4 and am trying to upload an image in a form. The problem I'm having is that when the form posts, if the <input type="file"... is empty (meaning I have not selected a file) the form posts just fine and everything works. However, When I do select a file the form just sits there and does nothing.
At first I thought it was just taking it a while to upload but I have left it for quite some time (file size was 7kb) and nothing. the debugger doesn't even hit the breakpoints at the beginning of the action either. I'm at a loss since I'm quite new to the platform and am still learning every day. Below please find all the relevant code:
the View:
@using (Html.BeginForm("StaffInformation", "Manager", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="control-group">
@Html.LabelFor(model => model.firstName, new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(model => model.firstName, new { @class = "span12" })
@Html.ValidationMessageFor(model => model.firstName)
</div>
</div>
<div class="control-group">
@Html.LabelFor(model => model.lastName, new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(model => model.lastName, new { @class = "span12" })
@Html.ValidationMessageFor(model => model.lastName)
</div>
</div>
<div class="control-group">
Staff Photo:
<div class="controls">
@if (Model.staffImage == null)
{
@:None
}else{
<img width="150" height="150" src="@Url.Action("GetImage", "Manager", new { Model.staffProfileID })" /><br />
}
<input type="file" id="staffImage" name="staffImage" data-provide="fileinput">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<a href="@Url.Action("dashboard", "manager")" class="btn" type="reset" >Cancel</a>
</div>
}
The Action:
public ActionResult StaffInformation(StaffInformationViewModel model, HttpPostedFileBase staffImage)
{
if (ModelState.IsValid) //This is where the breakpoint is
{
if (staffImage != null) {
model.imageMimeType = staffImage.ContentType;
model.staffImage = new byte[staffImage.ContentLength];
staffImage.InputStream.Read(model.staffImage, 0, staffImage.ContentLength);
}
using (var repo = new CompanyInformationRepository(new UniteOfWorkCompanies()))
{
var company = repo.FindCompany(User.Identity.Name);
repo.AddOrUpdateStaff(model, company);
}
return RedirectToAction("ManageStaff");
}
}
I really don't know whats going on and simply the reason I'm using the enctype = "multipart/form-data" is because I was reading the "Pro ASP.NET MVC 4" by Adam Freeman and in there they said that it won't work without it. Like I said, I'm quite new and need all the help I can get.