模型中的 HttpPostedFileBase 生成三个 <input type="file">
HttpPostedFileBase in model generates three <input type="file">
我遇到了一个每次都能重现的奇怪现象。
我的模型是:
[Display(Name = "Upload File")]
[DataType(DataType.Upload)]
public System.Web.HttpPostedFileBase file { get; set; }
我的剃刀是(我省略了 css 类):
@Html.LabelFor(m => m.file)
@Html.EditorFor(m => m.file, new { htmlAttributes = new { @type = "file" } })
以上给出:
三个<input type="file">
从哪里来的?
但是,如果在模型中我将 file
的类型更改为 string
(而不是 HttpPostedFileBase
),那么会显示一个 <input type="file">
。
如何在 Razor 页面中使用 Html 帮助程序来控制文件上传?
据我所知在 MVC 4 中,EditorFor
helper 还不支持 htmlAttributes
(this object
parameter is available for MVC 5.1 or above),通常是从 HttpPostedFileBase
属性 是通过使用 TextBoxFor
助手生成的:
@Html.TextBoxFor(m => m.file, new { type = "file" })
注:
在尝试在 EditorFor
中使用 htmlAttributes
时,我发现助手生成了其他 3 个输入,每个输入名为 ContentLength
、ContentType
和 FileName
,因此我怀疑助手从 HttpPostedFileBase
class 的几个 public 属性 成员而不是 属性 本身创建了输入。
如果要使用 EditorFor,则需要为 HttpPostedFileBase 指定一个。在 Views/Shared/EditorTemplates 下添加名为 HttpPostedFileBase.cshtml 的文件,内容如下(将构建设置为内容):
@model HttpPostedFileBase
@{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)
我遇到了一个每次都能重现的奇怪现象。
我的模型是:
[Display(Name = "Upload File")]
[DataType(DataType.Upload)]
public System.Web.HttpPostedFileBase file { get; set; }
我的剃刀是(我省略了 css 类):
@Html.LabelFor(m => m.file)
@Html.EditorFor(m => m.file, new { htmlAttributes = new { @type = "file" } })
以上给出:
三个<input type="file">
从哪里来的?
但是,如果在模型中我将 file
的类型更改为 string
(而不是 HttpPostedFileBase
),那么会显示一个 <input type="file">
。
如何在 Razor 页面中使用 Html 帮助程序来控制文件上传?
据我所知在 MVC 4 中,EditorFor
helper 还不支持 htmlAttributes
(this object
parameter is available for MVC 5.1 or above),通常是从 HttpPostedFileBase
属性 是通过使用 TextBoxFor
助手生成的:
@Html.TextBoxFor(m => m.file, new { type = "file" })
注:
在尝试在 EditorFor
中使用 htmlAttributes
时,我发现助手生成了其他 3 个输入,每个输入名为 ContentLength
、ContentType
和 FileName
,因此我怀疑助手从 HttpPostedFileBase
class 的几个 public 属性 成员而不是 属性 本身创建了输入。
如果要使用 EditorFor,则需要为 HttpPostedFileBase 指定一个。在 Views/Shared/EditorTemplates 下添加名为 HttpPostedFileBase.cshtml 的文件,内容如下(将构建设置为内容):
@model HttpPostedFileBase
@{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)