06-HtmlHelper使用Lambda方式使用

我们前面的日期控件,name字段都是直接传入字符串名称的,但是我们其实发现,mvc的一些HtmlHelper的带for的后缀的,比如@Html.PasswordFor

那么这些带For后缀的和不带For后缀的有什么区别呢?

带For后缀的,我们可以配合强类型视图模型来使用。

我们通过@model LoginViewModel

@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.TextBox("Email","admin@FoxDevelop.com", new { @class = "form-control" })Code language: JavaScript (javascript)

这样的方式来完成表单的渲染

下面我们就把上一节中的日期控件改造成Lambda的方式调用

关键方法签名

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)Code language: JavaScript (javascript)

ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

实现代码

//要实现带for的这种 关键两部 就是得到字段的name 和 
        public static MvcHtmlString DickPicketFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
        {
            //取得元数据
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            //取得字段的名称
            string name = ExpressionHelper.GetExpressionText(expression);
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            //取得字段的值
            object value = metadata.Model;

            var dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            TagBuilder tagBuilder = new TagBuilder("input");
            tagBuilder.MergeAttributes(dic);
            tagBuilder.MergeAttribute("class", "Wdate");
            tagBuilder.MergeAttribute("name", fullName, true);
            tagBuilder.MergeAttribute("onClick", "WdatePicker({ el:this, dateFmt:'yyyy-MM-dd HH:mm:ss' })");
            return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);
        }Code language: JavaScript (javascript)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注