简体   繁体   中英

Why RadioButtonFor userInput not binding to model?

When user selects the radioButton, IsSelected property is still false on postback, why?

View

在此处输入图片说明

@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>
}

Controller

在此处输入图片说明

If you have different types of option you could use following

A very simple way of implementing this would be something like this

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

or you can also use,

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

If you just want isSelected is true or false use this.

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

不确定是不是您的问题,但如果检查了比预期的错误,请尝试将值设置为true

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

The overload that you are using binds the value of the radio input element to the provided value - so you are generating markup like this:

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

When this gets submitted back to your controller .NET deserializes that value to a boolean - which in this case, is false .

To fix it, use true as the second argument:

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

Try this,

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

or

 @Html.RadioButton("IsSelected", true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM