有沒有辦法將視圖模型傳遞給@helper函數?從剃刀幫手中進入模型
我有一個顯示Yes/No/Maybe單選按鈕的自定義編輯器。這個編輯器的代碼如下所示。因爲它需要一個自定義的函數加上代碼,以顯示每個單選按鈕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,再加上我的額外代碼,包括「檢查」屬性,在一個呼叫,像這樣:
@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>
感謝Darin。我想我的問題並不清楚。我已經更新了更具體的問題。 –
@ Bob.at.SBS,在更新之後,它更清晰地表達你的想法。我已經用我的答案更新了一個如何實現這個目標的例子。 –