有没有办法将视图模型传递给 @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”属性的附加代码,如下所示:
@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>