我想转换我的
<input type="file" id="image" name="image">
类似
@Html.UploadFor(model => model.Image)
更多MVC友好......
我知道我必须使用Linq Expression功能为它创建一个帮助器。
如何做到这一点?
修改
这是一个解决方案:
public static MvcHtmlString UploadFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
var builder = new TagBuilder("input");
builder.MergeAttribute("type", "file");
builder.MergeAttribute("id", HtmlExtensions.IdFor(helper, expression));
builder.MergeAttribute("name", HtmlExtensions.NameFor(helper, expression));
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
public static class HtmlExtensions
{
public static string NameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
}
public static string IdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return HtmlHelper.GenerateIdFromName(NameFor(htmlHelper, expression));
}
}
答案 0 :(得分:2)
请参阅此参考/教程,了解如何创建自定义HTML帮助程序:http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
public static MvcHtmlString UploadFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
// generate your HTML
}