【问题标题】:HttpPostedFileBase in model generates three <input type="file">模型中的 HttpPostedFileBase 生成三个 <input type="file">
【发布时间】:2019-01-28 12:08:16
【问题描述】:

我正面临一个每次都能重现的奇怪现象。

我的模型是:

[Display(Name = "Upload File")]
[DataType(DataType.Upload)]
public System.Web.HttpPostedFileBase file { get; set; }

我的 Razor 是(我省略了 css 类):

@Html.LabelFor(m => m.file)
@Html.EditorFor(m => m.file, new { htmlAttributes = new { @type = "file" } })

以上给出:

&lt;input type="file"&gt;这三个是哪里来的?

但是,如果在模型中我将file 的类型更改为string(而不是HttpPostedFileBase),那么会显示一个&lt;input type="file"&gt;

如何在 Razor 页面中使用 Html 助手控制文件上传?

【问题讨论】:

  • 只有@Html.EditorFor(m =&gt; m.file) 就够了吗?我尝试在使用new { htmlAttributes = new { @type = "file" } } 时复制并获取其他 3 个输入,分别命名为 ContentLengthContentTypeFileName,但在使用 TextBoxFor 助手时却没有。
  • 不要使用编辑器。如果使用助手,则使用通过助手设置类型属性的文本框或手动提供具有必要属性的输入标签。编辑器将为绑定模型属性的公共属性创建输入
  • @Both,TextBoxFor 是否提供文件控制权?早些时候我尝试过,但它给了我一个文本框,尽管有明确的@type="file"
  • 我创建了a fiddle 以使用TextBoxFor 助手显示文件上传,确保属性类型也设置为HttpPostedFileBase。正如我测试的那样,EditorFor 尝试为HttpPostedFileBase 中的几个公共属性创建输入。

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

如果您想使用 EditorFor,您需要为 HttpPostedFileBase 指定一个。在 Views/Shared/EditorTemplates 下添加一个名为 HttpPostedFileBase.cshtml 的文件,其内容如下(将构建设置为内容):

@model HttpPostedFileBase
@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)

【讨论】:

    【解决方案2】:

    据我所知,在 MVC 4 中,EditorFor helper 还不支持htmlAttributes (this object parameter is available for MVC 5.1 or above),通常来自HttpPostedFileBase 属性的文件输入是使用TextBoxFor helper 生成的:

    @Html.TextBoxFor(m => m.file, new { type = "file" })
    

    注意:

    在尝试在EditorFor 中使用htmlAttributes 时,我发现助手生成了其他3 个输入,每个输入分别命名为ContentLengthContentTypeFileName,因此我怀疑助手从几个公共属性创建了输入HttpPostedFileBase 类的成员,而不是属性本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2017-11-26
      • 2012-06-15
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      相关资源
      最近更新 更多