MVC htmlhelp類擴展for lambda表達式方式
來源:程序員人生 發布時間:2015-02-03 08:36:58 閱讀次數:3092次
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());
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈