問題は、テンプレートに複数のHTML要素が含まれている可能性があるため、MVCはサイズ/クラスをどの要素に適用するかを認識しないことです。自分で定義する必要があります。
テンプレートをTextBoxViewModelという独自のクラスから派生させます。
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
}
public string GetAttributesString()
{
return string.Join(" ", moreAttributes.Select(x => x.Key + "='" + x.Value + "'").ToArray()); // don't forget to encode
}
}
テンプレートでは、これを行うことができます:
<input value="<%= Model.Value %>" <%= Model.GetAttributesString() %> />
あなたの見解では、あなたは次のことをします:
<%= Html.EditorFor(x => x.StringValue) %>
or
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue, new IDictionary<string, object> { {'class', 'myclass'}, {'size', 15}}) %>
最初のフォームは、文字列のデフォルトテンプレートをレンダリングします。2番目のフォームは、カスタムテンプレートをレンダリングします。
代替構文は流暢なインターフェースを使用します:
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
moreAttributes = new Dictionary<string, object>();
}
public TextBoxViewModel Attr(string name, object value)
{
moreAttributes[name] = value;
return this;
}
}
// and in the view
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) %>
ビューでこれを行う代わりに、コントローラーでこれを行うことも、ViewModelではるかに優れていることに注意してください。
public ActionResult Action()
{
// now you can Html.EditorFor(x => x.StringValue) and it will pick attributes
return View(new { StringValue = new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) });
}
また、基本のTemplateViewModelクラス(すべてのビューテンプレートの共通の基盤)を作成できることにも注意してください。これには、属性などの基本的なサポートが含まれます。
しかし、一般的に、MVCv2にはより良いソリューションが必要だと思います。それはまだベータ版です-それを求めに行きます;-)