私は 可能な場合は、これを制御するためのViewModelに設定された属性をしたいと思います。
ASP.NET MVCは、これを行うための拡張可能なシステムを提供します。あなたが何をする必要があるのです:
- カスタム
ModelMetadataProvider
を実装します。
StringLengthAttribute
またはMaxLengthAttribute
を探して、情報を抽出してModelMetadata
に追加します。
- 情報を使用するカスタムのエディタテンプレートを提供します。
ステップ1:カスタムModelMetadataProvider
を実装します。
ModelMetadataProvider
から派生するクラスを作成します。通常はDataAnnotationsModelMetadataProvider
から派生します。これはデフォルトの機能をいくつか提供します。つまり、CreateMetadata
という1つのメソッドをオーバーライドするだけです。
ステップ2:情報を抽出します。
情報を取得するには、属性を探し、最大の長さの情報を抽出し、ModelMetadata
のAdditionalValues
辞書に追加する必要があります。 ASP.NET MVCはあなたがGlobal.asax
でApplication_Start
方法でそれを登録する必要があり、これを使用するためには
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;
}
}
:実装は、この(これは全体の実装である)のようになります。
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その詳細をモデルメタデータ提供システムについての詳細をお知りになりたい場合は(これらは前にカミソリ・ビュー・エンジンに書き込まれたので、ビューの構文の一部は少しファンキーであるが、それ以外の情報音である)。
私は、拙速な解決策だったここで、似たように走った
6文字以上の文字列を送信できるかどうか確認しましたか? –
検証エラーが出ますが、実際にmaxlength属性を設定します。 –
'TextBoxFor'に変更すると、HTMLオプションを渡すことができます。 –