簡體   English   中英

為什么RadioButtonFor userInput無法綁定到模型?

[英]Why RadioButtonFor userInput not binding to model?

當用戶選擇單選按鈕時,回發時IsSelected屬性仍然為false ,為什么?

視圖

在此處輸入圖片說明

@using (Html.BeginForm())
{
    <fieldset>
        <legend>UserChoice</legend>

        @Html.DisplayNameFor(model => model.IsSelected)
        @Html.TextBoxFor(model => model.FirstName)

        @Html.RadioButtonFor(uc => uc.IsSelected, false)

        <input type="submit" name="name" value="Submit Form" />
    </fieldset>
}

調節器

在此處輸入圖片說明

如果您有其他類型的選項,則可以使用以下選項

一個很簡單的實現方法就是這樣

@Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option1")
@Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option2")
@Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option3")

或者您也可以使用

@Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option1)
@Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option2)
@Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option3)

如果只希望isSelectedtruefalse使用此方法。

@Html.RadioButtonFor(uc => uc.IsSelected, true)

不確定是不是您的問題,但如果檢查了比預期的錯誤,請嘗試將值設置為true

 @Html.RadioButtonFor(uc => uc.IsSelected, true)

您正在使用的重載radio輸入元素的值綁定到提供的值-因此您將生成如下標記:

<input type="radio" name="isSelected" value="false">

當這被提交回控制器時,.NET將該value反序列化為boolean -在這種情況下為false

要解決此問題,請使用true作為第二個參數:

@Html.RadioButtonFor(uc => uc.IsSelected, true)

嘗試這個,

@Html.RadioButtonFor(uc => uc.IsSelected, true)

要么

 @Html.RadioButton("IsSelected", true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM