Cipiripi
Cipiripi

Reputation: 1143

MVC - file upload

Hey... I have upload control on my view. Is there a way to associate this control with model data(something like LabelFor or TextBoxFor). I need this, because on page load I loose my information in file upload control Thx

Upvotes: 3

Views: 1713

Answers (2)

Paulius Zaliaduonis
Paulius Zaliaduonis

Reputation: 5189

HTML Upload File ASP MVC 3.

Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)

public class ViewModel
{
    [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
    public HttpPostedFileBase File { get; set; }
}

HTML View:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.File)
}

Controller action:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Use your file here
        using (MemoryStream memoryStream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(memoryStream);
        }
    }
}

Upvotes: 8

Paul
Paul

Reputation: 6218

Yes, use the HttpPostedFileBase class for the property type and it will bind just like any other property would.

Upvotes: 0

Related Questions