나는 인 경우 이것을 제어하기 위해 ViewModel에서 설정 한 속성을 원합니다.
ASP.NET MVC는이를 정확히 수행 할 수있는 확장 가능한 시스템을 제공합니다. 다음은 수행해야 할 작업입니다.
- 사용자 정의
ModelMetadataProvider
을 구현하십시오.
StringLengthAttribute
또는 MaxLengthAttribute
을 찾아 정보를 추출하여 ModelMetadata
에 추가하십시오.
- 정보를 사용하는 사용자 정의 편집기 템플릿을 제공하십시오.
1 단계 : 사용자 정의 ModelMetadataProvider
를 구현합니다.
ModelMetadataProvider
에서 파생되는 클래스를 만듭니다. 일반적으로 DataAnnotationsModelMetadataProvider
에서 파생됩니다. 기본 기능을 제공하기 때문에 CreateMetadata
이라는 단일 메서드 만 재정의하면됩니다.
2 단계 :가 정보를 추출 :
이 정보를 얻으려면, 당신은 속성을 찾아 최대 길이 정보를 추출하고 ModelMetadata
의 AdditionalValues
사전에 추가해야합니다. 구현 (이 전체 구현)과 같이 보일 것입니다 :
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
// Call the base class implementation to create the default metadata...
var metadata = base.CreateMetadata(
attributes,
containerType,
modelAccessor,
modelType,
propertyName);
// Extract the stringLengthAttribute (you can do the same for the
// MaxLengthAttribute if you want).
var attr = attributes
.OfType<StringLengthAttribute>()
.First();
// This could be getting called on a property that doesn't have the
// attribute so make sure you check for null!
if (attr != null)
{
metadata.AdditionalValues["maxLength"] = attr.MaximumLength;
}
return metadata;
}
}
위해 ASP.NET MVC 당신이 Global.asax
에 Application_Start
방법에 등록하기 위해 필요한이를 사용하는.
ModelMetadataProviders.Current = new CustomModelMetadataProvider();
3 단계 : 사용자 정의 편집기 템플릿을 만듭니다.
이제 정보를 사용하는보기를 만들어야합니다. Views\Shared\
폴더에 String
이라는 새보기를 만듭니다. String.cshtml
@{
object maxLength;
if (!ViewData.ModelMetadata.AdditionalValues
.TryGetValue("maxLength", out maxLength))
{
maxLength = 0;
}
var attributes = new RouteValueDictionary
{
{"class", "text-box single-line"},
{ "maxlength", (int)maxLength },
};
}
@Html.TextBox("", ViewContext.ViewData.TemplateInfo.FormattedModelValue, attributes)
당신이 @Html.EditorFor
를 호출하여 다음과 같은 HTML 출력을 얻을 것이다 응용 프로그램을 실행
.
<input class="text-box single-line" id="Extension" maxlength="6" name="Extension" type="text" value="" />
당신이 모델 메타 데이터 제공 시스템은 (이들은 면도기보기 엔진 이전에 기록 된 작동 방법을 자세히 그렇게보기 구문의 일부는 약간 펑키 것을 Brad Wilson has a series of blog posts하지만, 그렇지 않은 정보에 대해 더 알고 싶다면 소리입니다.) 당신의 HTML을 대체 EditorFor와의 아래에서
@{
var max = ((System.ComponentModel.DataAnnotations.StringLengthAttribute)(typeof(MyType))
.GetProperty("MyProp")
.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true)[0]).MaximumLength;
}
: 줄을 추가
당신의 .cshtml 파일의 상단에 :
6 자 이상의 문자열을 게시 할 수 있는지 확인 했습니까? –
유효성 검사 오류가 발생하지만 실제로 maxlength 속성을 설정해야합니다. –
'TextBoxFor'로 변경하면 HTML 옵션을 전달할 수 있습니다. –