4

RadioButtonFor ヘルパーの使用に問題があります。渡された値が true の場合、どちらのラジオ ボタンにも「チェック」が表示されません。値が false の場合、問題なく動作します。

私が取り組んでいるプロジェクトからこのコードをコピーしてサンプル アプリケーションを作成したところ、問題を再現することができました。値を true または false にハードコーディングすると動作するように見えますが、「!string.IsNullOrEmpty(allgroups)」を使用すると動作しません。

ビューから:

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

ViewModel から:

    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>
4

2 に答える 2

2

アクション パラメーターにモデル プロパティと同じ名前を付けたため、モデル バインディングが混乱しています。Indexアクション パラメータの名前を変更すると、機能するはずです。

public ActionResult Index(string showAllGroups)
{
    var model = new ProgramGroup
                    {
                        AllGroups = !string.IsNullOrEmpty(showAllGroups);
                    };
    return View(model);
}
于 2012-05-17T15:11:55.737 に答える
-1

モデルからboolを返す場合は、明示的にチェックを外す必要はありません。mvcはそれ自体を実行します。

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

ただし、明示的に実行したい場合は、

チェック/チェック解除するには、次の構文を使用する必要があります

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

ソースコードでは、チェックされていない属性に対してtrue/falseが設定されていることがわかります。

あなたの見解ではあなたは書くことができます

@if(m.AllGroups)
{
  Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { @checked = "checked" })
}
else
{
   Html.RadioButtonFor(m => m.AllGroups, "DisplayText" })
}
于 2012-05-17T04:39:51.007 に答える