3

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

2 Answers 2

8

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

I still have the same problem, value in uploadfile is lost when page is reloaded
Have you got enctype="multipart/form-data" set? (w3.org/TR/html401/interact/forms.html#adef-enctype)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.