ViewModelのプロパティに適用するカスタム表示属性(具体的には追加のhtml属性)の作成については、このガイドに従っています。EditorTemplatesフォルダーのStringとBooleanの両方をオーバーライドしました。エディターテンプレートは、値が設定されているか/表示属性が使用されているかを確認し、追加のhtml属性を追加します。
ただし、編集アクションを実行すると、ブール値のオーバーライドでスタックします。属性を文字列に適用するかどうかに関係なく、ViewModelは常に正しい既存のデータにマップされます。これは、TextBoxFor内のtype属性を変更することによってテンプレートが作成された方法のため、他のフォーム入力タイプには当てはまりません。
私はこれを主にノックアウトを掘り下げて書いていて、データバインド属性を強く型付けされたビューに適用する簡単な方法を望んでいました-より良い方法があれば教えてください!
属性コード:
public class Knockout : Attribute
{
public string DataBind { get; set; }
public string InputType { get; set; }
/*
Example:
Knockout("checked: showUploader", "checkbox")
Adds the HTML attributes data-bind="checked: showUploader" type="checkbox"
*/
public Knockout(string dataBind, string inputType)
{
this.DataBind = dataBind;
this.InputType = inputType;
}
public Dictionary<string, object> OptionalAttributes()
{
var options = new Dictionary<string, object>();
if(!string.IsNullOrWhiteSpace(DataBind))
{
options.Add("data-bind", DataBind);
}
if (!string.IsNullOrWhiteSpace(InputType))
{
options.Add("type", InputType);
}
return options;
}
}
テンプレートコード
@using CumbriaMD.Infrastructure.ViewModels.DisplayAttributes
@{
var key = "Knockout";
}
@if (ViewData.ModelMetadata.AdditionalValues.ContainsKey(key))
{
var knockout = ViewData.ModelMetadata.AdditionalValues[key] as Knockout;
@Html.TextBoxFor(model => model, knockout.OptionalAttributes())
}
else
{
/*
When the attribute is not present, the default action is the following - which seems to
be overriding the data mapped from the database:
*/
@Html.TextBoxFor(model => model, new { type="checkbox" })
}