2012-05-17 27 views
3

我遇到了使用RadioButtonFor幫助器的問題。當傳入的值爲真時,它不顯示任何一個單選按鈕中的「檢查」。當該值爲假時,它工作得很好。使用Html.RadioButtonFor與布爾值不寫入Checked =「Checked」

我從我正在處理的項目中複製了該代碼並創建了一個示例應用程序,我能夠複製該問題。如果我硬編碼值爲真或假它似乎工作,但是當我使用「!string.IsNullOrEmpty(allgroups)」它不。

從視圖:

<div> 
    @Html.RadioButtonFor(m => m.AllGroups, true) All Groups 
    @Html.RadioButtonFor(m => m.AllGroups, false) Current Groups 
</div> 

從視圖模型:

public bool AllGroups { get; set; } 

從控制器:

public ActionResult Index(string allgroups) 
{ 
    var model = new ProgramGroupIndexViewModel 
     { 
      AllGroups = !string.IsNullOrEmpty(allgroups) 
     }; 
    return View(model); 
} 

從視圖源在IE:

<div> 
    <input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups 
    <input id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups 
</div> 

從查看源代碼時AllGroups的值爲false(注意它的工作原理):

<div> 
    <input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups 
    <input checked="checked" id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups 
</div> 

回答

2

模型結合越來越困惑,因爲你命名你的行動參數與您的模型屬性相同。更改您的Index操作參數的名稱,它應該有效。

public ActionResult Index(string showAllGroups) 
{ 
    var model = new ProgramGroup 
        { 
         AllGroups = !string.IsNullOrEmpty(showAllGroups); 
        }; 
    return View(model); 
} 
-1

如果從模型返回布爾那麼就沒有必要檢查取消明確MVC將做到這一點本身就寫

<div> 
    @Html.RadioButtonFor(m => m.AllGroups) 
    @Html.RadioButtonFor(m => m.AllGroups) 
</div> 

但是如果你想這樣做,然後明確

你應該使用下面的語法檢查/取消

Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { @checked = "checked" }) 

在源代碼中,你可以看到,它是設置真/假的值未選中屬性

在你看來,你可以寫

@if(m.AllGroups) 
{ 
    Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { @checked = "checked" }) 
} 
else 
{ 
    Html.RadioButtonFor(m => m.AllGroups, "DisplayText" }) 
} 
+0

@ Html.RadioButtonFor(m => m.AllGroups)是一個錯誤「無法解析方法」。 – Dean

+0

同意,不起作用。 – mbp