본문 바로가기

.NET/MVC.NET

Custom Attribute만들기와 메타데이터 등록

MVC.NET의 많은 기능들 중에서 태그에 Attribute를 삽입할때 아래와 같이 합니다.
@Html.TextBoxfor(model=>model.Name, new {style="display:none"}
위와 같이 익명 Object를 사용해서 어트리뷰트를 지정하는 것보다 다른 방법으로 즉, Model Class에 Attribute를 지정하여 사용하는 방법을 배워 보겠습니다. 

순서대로 따라 해 보세요
1. CustomHtmlAttribute생성

public class CustomHtmlAttribute : Attribute 
	{
		public int MaxLength { getset;}
		public bool ReadOnly { getset; }
		public bool Disabled { getset; }
		public string Class { getset; }
 
		public Dictionary<stringobject> SetAttributes() 
		{
			var attributes = new Dictionary<stringobject>();
			if (MaxLength > 0)
				attributes.Add("maxlength",MaxLength);
			if (ReadOnly)
				attributes.Add("readonly""readonly");
			if (Disabled)
				attributes.Add("disabled""disabled");
			if (!String.IsNullOrWhiteSpace(Class))
				attributes.Add("class", Class);
			return attributes;
		}
	}
2. MetaDataProvider 생성

public class MetaDataProvider : DataAnnotationsModelMetadataProvider 
	{
		protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
		{
			var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
			var additionalvalues = attributes.OfType<CustomHtmlAttribute>().FirstOrDefault();
			if (additionalvalues != null)
				metadata.AdditionalValues.Add("CustomHtmlAttribute", additionalvalues);
			return metadata;
		} 
}
3. Model 생성
public class UserInfo
	{
		public string FirstName { getset; }
		public string LastName { getset; }
}
4. ModelMetaData생성
	public class UserInfoMetaData
	{ 
		[CustomHtml(MaxLength=10, Disabled=false, Class="input")]
		public string FirstName { getset; }
 
		[CustomHtml(MaxLength = 10, Disabled = false, Class = "input")]
		public string LastName { getset; }
 
}  5.Razor를 이용한 View사용법
@{
	var key = "CustomHtmlAttribute";
}
@if (ViewData.ModelMetadata.AdditionalValues.ContainsKey(key)) 
{
	var customHtml = ViewData.ModelMetadata.AdditionalValues[key] as MvcApplication3.Controllers.CustomHtmlAttribute;
	@Html.TextBoxFor(model => model.FirstName,customHtml.SetAttributes());
}}

6. MetaDataProvider등록
	protected void Application_Start()
	{
ModelMetadataProviders.Current = new MetaDataProvider();
 }

결과
<input class="input" id="FirstName" maxlength="10" type="text" value=""/>