Reputation: 1265
I'm attempting to upload a number and a file through an Html-Helper form in my MVC 5 application. After submitting the model, it seems that my model.File
property from the view model always returns null
.
Before adding the model.File != null
check, my application was throwing a NullReferenceException
.
I have my form logic contained in a partial view called UploadFile.cshtml
, since my form logic requires a different model than my index.cshtml
.
How do I read the File
property from my form in my [HttpPost]
controller action?
index.cshtml
@Html.Action("UploadFile", "Home")
UploadFile.cshtml
@model FileViewModel
@using (Html.BeginForm("FormUpload", "Home", FormMethod.Post))
{
<div class="form-group">
@Html.TextBoxFor(m => m.Marker)
</div>
<div class="form-group">
@Html.TextBoxFor(m => m.File, new { type = "file" })
</div>
<input type="submit" name="submit" value="Submit" />
}
HomeController
public PartialViewResult UploadFile()
{
return PartialView("UploadFile", new FileViewModel());
}
// /Home/FormUpload
[HttpPost]
public ActionResult FormUpload(FileViewModel model)
{
if (ModelState.IsValid)
{
if (model.File != null && model.File.ContentLength > 0 && model.File.ContentType == "application/pdf")
{
// Convert file to byte[] and upload
// ...
ViewBag.Message = "File Uploaded Successfully";
}
else
{
ViewBag.Message = "File Not Uploaded";
}
}
return RedirectToAction("Index");
}
FileViewModel
public class FileViewModel
{
public int ID { get; set; }
public int Marker { get; set; }
public string Filename { get; set; }
public HttpPostedFileBase File { get; set; }
}
Upvotes: 3
Views: 6457
Reputation: 23
Html.BeginForm("FormUpload", "Home", FormMethod.Post))
should be
@using (Html.BeginForm("FormUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
Upvotes: 2
Reputation: 62498
You are missing enctype attribute for the form, you need to specify that for file case:
@using (Html.BeginForm("FormUpload", "Home",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
See this article for further details.
Upvotes: 4