Can EditorFor() be used to create <input type=“file”>?

前端 未结 4 665
名媛妹妹
名媛妹妹 2020-12-16 11:16

Given this model, is it possible to use the Html.EditorFor() to render a file upload input element to the page? I played around with the Datatype of the property FileName,

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 11:30

    It would make more sense to use HttpPostedFileBase to represent an uploaded file on your view model instead of string:

    public class DR405Model
    {
        [DataType(DataType.Text)]
        public string TaxPayerId { get; set; }
    
        [DataType(DataType.Text)]
        public string ReturnYear { get; set; }
    
        public HttpPostedFileBase File { get; set; }
    }
    

    then you could have the following view:

    <% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    
        ... input fields for other view model properties
    
        
    <%= Html.EditorFor(model => model.File) %> <%= Html.ValidationMessageFor(model => model.File) %>
    <% } %>

    And finally define the corresponding editor template inside ~/Views/Shared/EditorTemplates/HttpPostedFileBase.ascx:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    " id="<%: ViewData.TemplateInfo.GetFullHtmlFieldId("") %>" />
    

    Now the controller might look like this:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new DR405Model());
        }
    
        [HttpPost]
        public ActionResult Index(DR405Model model)
        {
            if (model.File != null && model.File.ContentLength > 0)
            {
                var fileName = Path.GetFileName(model.File.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                model.File.SaveAs(path);
            }
    
            return RedirectToAction("Index");
        }
    }
    

提交回复
热议问题