naveed ahmed naveed ahmed - 21 days ago 11
C# Question

File HttpPostedFileBase upload post NULL on partial view MVC

I am working on multiple file post, I am using

HttpPostedFileBase
.

When submitting the form, the
file
property is
null
.

Model

public partial class Driver
{
public int DriverId { get; set; }
public string DriverFirstName { get; set; }
....
public List<DriverImages> DriverImages { get; set; }
}

public class DriverImages
{
public int DriverImageID { get; set; }
public string ImagePath { get; set; }
public string Description { get; set; }
public HttpPostedFileBase file { get; set; }
}


Partial view

@model DataModel.DriverImages
...
@using (Design.Common.HtmlPrefixScopeExtensions.BeginCollectionItem(this.Html, "DriverImages"))
{
<table>
<tr>
<td>
@Html.TextBoxFor(m => Model.Description)
</td>
<td>
<input type="file" name="file" />
</td>
</tr>
</table>
}


Controller

[httppost]
public ActionResult Create(Driver ObjDriverModel, HttpPostedFileBase[] files)
{
// ObjDriverModel.DriverImages.file // always null
}

Answer

You not generating a file input for your model property. It needs to be

<td>
    @Html.TextBoxFor(m => m.Description)
</td>
<td>
    @Html.TextBoxFor(m => m.file, new { @type = "file" })
</td>

This will generate

<input type="file" name="DriverImages[xxx].file" .... />

where xxx is a Guid

and remove the HttpPostedFileBase[] file parameter from your method (note you would have received them have you renamed the parameter to file to match the property name, but then they would not have matched up to your model if any of the file inputs were empty).