In this article I will explain with an example, how to set enctype = ‘multipart/form-data’ attribute for Form Tag with Html.BeginForm Helper method in ASP.Net MVC Razor.
The enctype = ‘multipart/form-data’ attribute is required when the Form is used for uploading Files using HTML FileUpload element.
 
 
Configuring Bundles and enabling Client Side Validation
Please refer the following article for complete information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.
 
 
Regular Expression
The following Regular Expression is used for validating the selected file in HTML Fileupload element using its extension.
The Regular Expression can be modified to be used for multiple File extensions by simply adding and removing the extensions.
Note: The File Extensions must be separated by Pipe (|) character and must be prefixed with Dot (.) character.
 
Regular Expression for allowing Word Document and PDF files only
([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$
 
Regular Expression for allowing Image files only
([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$
 
Regular Expression for allowing Text files only
([a-zA-Z0-9\s_\\.\-:])+(.txt)$
 
Regular Expression for allowing Excel files only
([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$
 
 
Model
The following Model class consists of one property PostedFile to which the following validation Data Annotation attributes have been applied.
1. Required Data Annotation attribute.
2. RegularExpression Data Annotation attribute.
The RegularExpression Data Annotation attribute accepts the Regular Expression as first parameter. The Regular expression will allow only Image files of type PNG, JPG and GIF.
The Required Data Annotation and the RegularExpression Data Annotation attributes have been specified with a property Error Message with a string value. As the name suggests, this string value will be displayed to the user when the respective validation fails.
public class FileModel
{
    [Required(ErrorMessage = "Please select file.")]
    [RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$", ErrorMessage = "Only Image files allowed.")]
    public HttpPostedFileBase PostedFile { get; set; }
}
 
 
Namespaces
You will need to import the following namespace.
using System.IO;
 
 
Controller
The Action method Index by default supports the GET operation and hence another overridden method for POST operation is created which accepts the parameter of type HttpPostedFileBase.
Note: The name of the HttpPostedFileBase parameter and the name of Model Property must be exact same, otherwise the HttpPostedFileBase parameter will be NULL.
 
First a check is performed whether Directory (Folder) exists if not then the Directory (Folder) is created and then the file is saved to the Directory (Folder).
Finally a message is displayed to the user using ViewBag. For more details on displaying message using ViewBag, please refer my article Display (Pass) String Message from Controller to View in ASP.Net MVC.
public class HomeController : Controller
{
    // GET: Home
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        string path = Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        if (postedFile != null)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            postedFile.SaveAs(path + fileName);
            ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
        }
 
        return View();
    }
}
 
 
View
Inside the View, in the very first line the FileModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
Inside the View, the following two HTML Helper functions are used:-
1. Html.TextBoxFor – Creating a Fileupload element for the Model property. The type attribute is specified as file and hence the output is an HTML Fileupload element instead of TextBox.
2. Html.ValidationMessageFor – Displaying the Validation message for the property.
There is also Submit button which when clicked, the Form gets submitted.
The jQuery and the jQuery Validation script bundles are rendered at the end of the Model using the Scripts.Render function.
@model FileUpload_Validation_MVC.Models.FileModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <span>Select File:</span>
            @Html.TextBoxFor(m => m.PostedFile, new { type = "file"})
            <br/>
            @Html.ValidationMessageFor(m => m.PostedFile, "", new { @class = "error" })
            <hr/>
            <input type="submit" value="Upload"/>
            <br/>
            <span style="color:green">@Html.Raw(ViewBag.Message)</span>
        }
    </div>
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>
 
 
Screenshot
ASP.Net MVC Html.BeginForm: Set enctype = ‘multipart/form-data’
 
 
Downloads