是否有用于文件上传的HTMLHelper
?具体地说,我正在寻找一个替代
<input type="file"/>
使用ASP.NET MVC HTMLHelper。
或者,如果我使用
using (Html.BeginForm())
文件上传的HTML控件是什么?
发布于 2011-06-15 03:17:46
您还可以使用:
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload" size="23" />
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
发布于 2008-11-20 10:34:43
不久前,我遇到了同样的问题,偶然发现了Scott Hanselman的一篇帖子:
Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
希望这能有所帮助。
发布于 2016-08-04 17:37:05
或者,您可以正确地执行此操作:
在您的HtmlHelper扩展类中:
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
return helper.FileFor(expression, null);
}
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var builder = new TagBuilder("input");
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
builder.GenerateId(id);
builder.MergeAttribute("name", id);
builder.MergeAttribute("type", "file");
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
这一行:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
生成一个对模型唯一的id,你知道在列表和其他东西中。model.Name等。
在模型中创建正确的属性:
public HttpPostedFileBase NewFile { get; set; }
然后您需要确保您的表单将发送文件:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
然后这是你的帮手:
@Html.FileFor(x => x.NewFile)
https://stackoverflow.com/questions/304617
复制相似问题