Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a HttpPostedFileBase to a controller method

I'm just trying to create a form where I can enter a name and upload a file. Here's the view model:

public class EmployeeViewModel
{
    [ScaffoldColumn(false)]
    public int EmployeeId { get; set; }

    public string Name { get; set; }

    public HttpPostedFileBase Resume { get; set; }
}

My view:

@using (Html.BeginForm("Create", "Employees", FormMethod.Post))
{   
    @Html.TextBoxFor(model => model.Name)

    @Html.TextBoxFor(model => model.Resume, new { type = "file" })

    <p>
        <input type="submit" value="Save" />
    </p>

    @Html.ValidationSummary()
}

And my controller method:

[HttpPost]
public ActionResult Create(EmployeeViewModel viewModel)
{
    // code here...
}

The problem is that when I post to the controller method, the Resume property is null. The Name property gets passed just fine, but not the HttpPostedFileBase.

Am I doing something wrong here?

like image 564
Steven Avatar asked Mar 01 '12 04:03

Steven


People also ask

How to upload a file using HTTP posted file base?

To upload a file in json, the client script must convert the file content to data url string and pass as a parameter (httppostedfilebase will be null). to use HttpPostedFileBase the post must be multi-part, in this case the the form must contain in a file field and a new FormData () object must be passed instead of json (the jquery must be.

How to add PostPost data to controller using jQuery Ajax?

Post Data To Controller Using jQuery Ajax in ASP.NET MVC 1 "Start", then "All Programs" and select "Microsoft Visual Studio 2015". 2 "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a... More ...

What is httppostedfilewrapper class?

The HttpPostedFileWrapper class derives from the HttpPostedFileBase class. The HttpPostedFileWrapper class serves as a wrapper for the HttpPostedFile class. At run time, you typically use an instance of the HttpPostedFileWrapper class to call members of the HttpPostedFile object.

How to pass value to action method from view to controller?

Please Sign up or sign in to vote. When you want to passed any value to action method then specify the RouteValues. Here is example. The RouteValues is used for passing value from view to controller. The parameter name should be similar as per routevalue. Also don't miss that Action method name 'Index'. ;) Please Sign up or sign in to vote.


1 Answers

Add the enctype to your form:

@Html.BeginForm("Create", "Employees", FormMethod.Post, 
                 new{ enctype="multipart/form-data"})
like image 184
Marc Avatar answered Oct 19 '22 02:10

Marc