0

I have the following _CreateOrEditPartial partial view which contain a text & a file upload:-

@model TMS.Models.DataCenter
@* This partial view defines form fields that will appear when creating and editing entities *@
@Html.AntiForgeryToken()

<div>
    <span class="f">Name </span>    
    @Html.EditorFor(model=>model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>
<div>
    <span class="f">Data Center Picture </span>    
    <input type="file" name="DataCenterfile" />
</div>

and the following main view :-

@using (Html.BeginForm("Create","DataCenter", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    @Html.Partial("_CreateOrEdit", Model)
    <input type="submit" value="Create" class="btn btn-primary"/>
}

Which will call the following ActionMethod:-

[HttpPost]
[ValidateAntiForgeryToken]
[CheckUserPermissions(Action = "Edit", Model = "DataCenter")]
public ActionResult Create(DataCenter dc, HttpPostedFileBase DataCenterfile)
{
    // Verify that the user selected a file
    if (DataCenterfile != null && DataCenterfile.ContentLength > 0)
    {
        // extract only the fielname
        var fileName = Path.GetFileName(DataCenterfile.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        DataCenterfile.SaveAs(path);
    }

but the datacenterfile will always be null .. can anyone advice what is causing this problem? Thanks

alexmac
  • 19,087
  • 7
  • 58
  • 69

1 Answers1

1

You forgot to add the enctype attribute to your form.

Something like this:

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

}

About enctype attribute: What does enctype='multipart/form-data' mean?

Community
  • 1
  • 1
Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55