【发布时间】: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" } })
以上给出:
<input type="file">这三个是哪里来的?
但是,如果在模型中我将file 的类型更改为string(而不是HttpPostedFileBase),那么会显示一个<input type="file">。
如何在 Razor 页面中使用 Html 助手控制文件上传?
【问题讨论】:
-
只有
@Html.EditorFor(m => m.file)就够了吗?我尝试在使用new { htmlAttributes = new { @type = "file" } }时复制并获取其他 3 个输入,分别命名为ContentLength、ContentType和FileName,但在使用TextBoxFor助手时却没有。 -
不要使用编辑器。如果使用助手,则使用通过助手设置类型属性的文本框或手动提供具有必要属性的输入标签。编辑器将为绑定模型属性的公共属性创建输入
-
@Both,
TextBoxFor是否提供文件控制权?早些时候我尝试过,但它给了我一个文本框,尽管有明确的@type="file"。 -
我创建了a fiddle 以使用
TextBoxFor助手显示文件上传,确保属性类型也设置为HttpPostedFileBase。正如我测试的那样,EditorFor尝试为HttpPostedFileBase中的几个公共属性创建输入。
标签: asp.net-mvc asp.net-mvc-4 razor