ビューモデルを @helper 関数に渡す方法はありますか?
はい/いいえ/多分ラジオ ボタンを表示するカスタム エディターがあります。このエディターのコードを以下に示します。各ラジオ ボタンを表示するには、カスタム関数と 3 行のコードが必要なので、各ラジオ ボタンとそれに関連付けられたラベルを作成するコードをグローバル @helper 関数にカプセル化したいと思いますが、その方法がわかりません。 RadioButtonFor をグローバル ヘルパー関数に移動します。
ボブ
これは既存のコードです:
@model System.String
@functions {
// Returns an anonymous object that specifies the radio button HTML options
private object HTMLOptions(string id, bool @checked) {
if (@checked) {
return new { id, @checked = "checked" };
} else {
return new { id };
}
}
}
@{
string value = Model + "";
string id;
}
<div class="option-list">
@{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioYes");}
@Html.RadioButtonFor(q => q, "true", HTMLOptions(id, value == "true"))
@Html.LabelFor(q => q, "Yes", new {@for = id})
<br />
@{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioNo");}
@Html.RadioButtonFor(q => q, "false", HTMLOptions(id, value == "false"))
@Html.LabelFor(q => q, "No", new {@for = id})
<br />
@{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioMaybe");}
@Html.RadioButtonFor(q => q, "maybe", HTMLOptions(id, value == "maybe"))
@Html.LabelFor(q => q, "Maybe", new {@for = id})
<br />
</div>
次のように、RadioButtonFor と LabelFor をカプセル化する汎用ヘルパーと、「checked」属性を含めるための追加コードを 1 回の呼び出しで記述できるようにしたいと考えています。
@model something
<div class="option-list">
@MyRadioButtonAndLabelFor(q => something.x, "Yes", "true") @* (model, label, value) *@
@MyRadioButtonAndLabelFor(q => something.x, "No", "false")
@MyRadioButtonAndLabelFor(q => something.x, "Maybe", "maybe")
</div>