Html helper for <input type=“file” />

后端 未结 8 2038
予麋鹿
予麋鹿 2020-11-28 18:16

Is there a HTMLHelper for file upload? Specifically, I am looking for a replace of


using ASP.NET

8条回答
  •  生来不讨喜
    2020-11-28 19:15

    Improved version of Paulius Zaliaduonis' answer:

    In order to make the validation work properly I had to change the Model to:

    public class ViewModel
    {
          public HttpPostedFileBase File { get; set; }
    
            [Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
            public string FileName
            {
                get
                {
                    if (File != null)
                        return File.FileName;
                    else
                        return String.Empty;
                }
            }
    }
    

    and the view to:

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

    This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.

提交回复
热议问题