可以使用EditorFor创建<input type =“ file”>吗?

问题描述

| 给定此模型,是否可以使用Html.EditorFor()将文件上传输入元素呈现到页面?我使用了FileName属性的Datatype,它肯定会影响呈现的编辑器表单。
public class DR405Model
{
    [DataType(DataType.Text)]
    public String TaxPayerId { get; set; }
    [DataType(DataType.Text)]
    public String ReturnYear { get; set; }

    public String  FileName { get; set; }
}
强类型* .aspx页面如下所示
    <div class=\"editor-field\">
        <%: Html.EditorFor(model => model.FileName) %>
        <%: Html.ValidationMessageFor(model => model.FileName) %>
    </div>
    

解决方法

使用HttpPostedFileBase代表视图模型上的上传文件而不是
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; }
}
那么您可以拥有以下视图:
<% using (Html.BeginForm(\"Index\",\"Home\",FormMethod.Post,new { enctype = \"multipart/form-data\" })) { %>

    ... input fields for other view model properties

    <div class=\"editor-field\">
        <%= Html.EditorFor(model => model.File) %>
        <%= Html.ValidationMessageFor(model => model.File) %>
    </div>

    <input type=\"submit\" value=\"OK\" />
<% } %>
最后在ѭ5define中定义相应的编辑器模板:
<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>
<input type=\"file\" name=\"<%: ViewData.TemplateInfo.GetFullHtmlFieldName(\"\") %>\" id=\"<%: ViewData.TemplateInfo.GetFullHtmlFieldId(\"\") %>\" />
现在控制器可能看起来像这样:
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\");
    }
}
    ,这是MVC 5的示例(对于htmlAttributes是必需的)。 在〜\\ Views \\ Shared \\ EditorTemplates下将其创建为名为HttpPostedFileBase.cshtml的文件
@model HttpPostedFileBase
@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData[\"htmlAttributes\"]);
    htmlAttributes[\"type\"] = \"file\";
}
@Html.TextBoxFor(model => model,htmlAttributes)
这将生成具有正确ID和名称的控件,并且在从模型EditorFor模板编辑集合时可以工作。     ,添加:htmlAttributes = new {type = \“ file \”}
<div class=\"editor-field\">
    <%: Html.EditorFor(model => model.FileName,new { htmlAttributes = new { type = \"file\" }) %>
    <%: Html.ValidationMessageFor(model => model.FileName) %>
</div>
注意:我正在使用MVC 5,但尚未在其他版本上进行测试。     ,不,请看一下http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...