MVC 扩展方法特点
.NET MVC 3中扩展方法特点:
(1)扩展类的名称以Extensions结尾;
(2)扩展类的类型是static;
(3)扩展方法至少有一个参数,第一个参数必须指定该方法作用于哪个类型,并且该参数以this修饰符为前缀;
(4)扩展方法的类型是static;
(5)如果拓展方法的返回值是字符串则返回类型是MvcHtmlString,而不是string;
(6)页面调用必须用using指令导入扩展类型所在的命名空间。
- <label for="Address">Address:</label>
- <%= Html.TextBox("user.Address")%>
- <%= Html.ValidationMessage("user.Address")%>
- var errors = DataAnnotationsValidationRunner.GetErrors(user);
- if (errors.Any())
- {
- new RulesException(errors).AddModelStateErrors(ModelState,"user");
- }
- public static IEnumerable<ErrorInfo> GetErrors(object instance)
- {
- var metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true)
- .OfType<MetadataTypeAttribute>().FirstOrDefault();
- var buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();
- var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
- var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();
- return from buddyProp in buddyClassProperties
- join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
- from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
- where !attribute.IsValid(modelProp.GetValue(instance))
- select new ErrorInfo(buddyProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
- }