How to create MVC 4 @Html.TextBox type="file"?

You can use the below syntax

@Html.TextBoxFor(model=>model.Email, new { @type="file", @class="input-file" })

Model

public class FeedbackForm
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    public string AdditionalInformation { get; set; }
    public HttpPostedFileBase ProjectInformation { get; set; }
}

View

@model FeedbackForm

@Html.TextBox("Name")
@Html.TextBox("Email")
...
@Html.TextBox("ProjectInformation", null, new { type="file", @class="input-file" })

// submit button

My recommended view (strongly - typed)

@model FeedbackForm

@Html.TextBoxFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Email)
...
@Html.TextBoxFor(model=>model.ProjectInformation, null, new { type="file", @class="input-file" })

// submit button

Controller

[HttpPost]
public ActionResult FeedbackForm(FeedbackForm model)
{
    // this is your uploaded file
    var file = model.ProjectInformation;
    ...

    return View();
}

MVC is using name convention, so if your textbox and model names match, then MVC will bind your inputs to your model.


I think you are getting a null because you have not specified the enctype in your form tag.

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

A working example always help.

Visit http://www.mindstick.com/Articles/cf1e1dd9-fdba-4617-94f0-407223574447/?Upload%20File%20in%20Asp.Net%20Mvc%204