MVC - file download

Hey ... I have download control in my view. Is there a way to associate this control with model data (something like LabelFor or TextBoxFor). I need this because when I load a page, I lose my information in managing file uploads, thanks

+3
source share
2 answers

HTML ASP MVC 3 Download File

Model : (Note that FileExtensionsAttribute is available in MvcFutures. It will check actions on the 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);
        }
    }
}
+8
source

Yes, use the HttpPostedFileBase class for the property type, and it will bind in the same way as any other property.

0
source

Source: https://habr.com/ru/post/1784727/


All Articles