加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

MVC htmlhelp类扩展for lambda表达式方式

发布时间:2020-12-13 20:13:43 所属栏目:PHP教程 来源:网络整理
导读:public static MvcHtmlString InputTextForTModel,TValue(this HtmlHelperTModel html,ExpressionFuncTModel,TValue expression,object attr=null) { DisplayAttribute disp = null; VilidateAttribute vilidate = null; string name = string.Empty; try { d
public static MvcHtmlString InputTextFor<TModel,TValue>(this HtmlHelper<TModel> html,Expression<Func<TModel,TValue>> expression,object attr=null)
        {
            DisplayAttribute disp = null;
            VilidateAttribute vilidate = null;
            string name = string.Empty;
            try
            {
                dynamic exp = expression.Body.GetType().GetProperty("Member").GetValue(expression.Body,null);
                var strName = (string)exp.Name;
                var p = typeof(TModel).GetProperty(strName);
                disp = p.GetCustomAttributes(typeof(DisplayAttribute),false).FirstOrDefault() as DisplayAttribute;
                vilidate = p.GetCustomAttributes(typeof(VilidateAttribute),false).FirstOrDefault() as VilidateAttribute;
                name = strName;
            }
            catch (Exception e)
            {
            }
            TagBuilder tag = new TagBuilder("input");
            tag.MergeAttribute("type","text");
            tag.MergeAttribute("class","form-control");
            tag.MergeAttribute("id","i-"+ name);
            tag.MergeAttribute("name","n-"+ name);
            tag.MergeAttribute("placeholder","请输入" + disp.Name);
            //验证
            foreach (var item in vilidate.GetInfo())
            {
                tag.MergeAttribute(item.Key,item.Value);
            }
            //附加
            if(attr!=null)
            {
                foreach (var item in attr.GetType().GetProperties(Reflection.BindingFlags.Instance | Reflection.BindingFlags.Public))
                {
                    tag.MergeAttribute(item.Name,item.GetValue(attr,null).ToString());
                }
            }
            tag.InnerHtml = disp == null ? "未设置Display" : "";
            return new MvcHtmlString(tag.ToString());
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读