Asp.net-Mvc
MVC3 EditorTemplate 用於使用 RadioButtons 的可為空的布爾值
我的一個對像上有一個可以為空的布爾值的屬性,我希望我的邏輯具有 true 表示 Yes,false 表示 No,null 表示 N/A。現在因為我將在許多不同的對像上擁有多個這樣的屬性,所以為這些屬性創建一個編輯器並顯示模板是最有意義的。在這一切都工作之後,我將使用 jQuery UI 應用按鈕集的視覺元素,但現在,這超出了我的問題範圍。我的編輯器模板看起來像這樣。
@model bool? <div data-ui="buttonset"> @Html.RadioButtonFor(x => x, true, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"}) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label> @Html.RadioButtonFor(x => x, false, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label> @Html.RadioButtonFor(x => x, "null", new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA">N/A</label> </div>我的問題是,在任何情況下我都無法讓這個編輯器模板正確顯示模型的目前值。因為我不是在這個範圍內渲染模型的屬性,而是模型本身,所以 MVC3 中的內置邏輯不會正確設置選中的屬性,因為進行了檢查以驗證名稱是否為空或 null(參見 MVC3源,InputExtensions.cs:line#259)。我無法通過與模型進行比較來動態設置選中的屬性,因為瀏覽器會檢查單選按鈕是否存在選中的屬性而不是它的值,所以即使我的單選按鈕看起來像下面的最後一個仍然是選中的.
<div class="span-4" data-ui="buttonset"> <input checked="checked" id="MyObject_BooleanValueYes" name="MyObject.BooleanValue" type="radio" value="True" /><label for="MyObject_BooleanValueYes">Yes</label> <input checked="" id="MyObject_BooleanValueNo" name="MyObject.BooleanValue" type="radio" value="False" /><label for="MyObject_BooleanValueNo">No</label> <input checked="" id="MyObject_BooleanValueNA" name="MyObject.BooleanValue" type="radio" value="null" /><label for="MyObject_BooleanValueNA">N/A</label> </div><span class="field-validation-valid" data-valmsg-for="MyObject.BooleanValue" data-valmsg-replace="true"></span> </div>我不能有條件地添加 HtmlAttribute 使用類似
if?truevalue:falsevalue的東西,因為真/假部分將是不同的匿名類型,我得到一個錯誤。我正在努力解決這個問題,希望你們中的一個人對如何解決這個問題有建議?
@model bool? <div data-ui="buttonset"> @{ Dictionary<string, object> yesAttrs = new Dictionary<string, object>(); Dictionary<string, object> noAttrs = new Dictionary<string, object>(); Dictionary<string, object> nullAttrs = new Dictionary<string, object>(); yesAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"); noAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No"); nullAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA"); if (Model.HasValue && Model.Value) { yesAttrs.Add("checked", "checked"); } else if (Model.HasValue && !Model.Value) { noAttrs.Add("checked", "checked"); } else { nullAttrs.Add("checked", "checked"); } } @Html.RadioButtonFor(x => x, "true", yesAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label> @Html.RadioButtonFor(x => x, "false", noAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label> @Html.RadioButtonFor(x => x, "null", nullAttrs) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA">N/A</label> </div>