【问题标题】:MVC Radiobutton default value did not set after knockout data-bind敲除数据绑定后未设置 MVC 单选按钮默认值
【发布时间】:2014-10-16 09:16:43
【问题描述】:

我正在使用 MVC 强类型视图来生成两个单选按钮

<div>
       @Html.LabelFor(model => model.Eligible)
        @Html.RadioButtonFor(model => model.Eligible,"true", new { id="yes", data_bind =       "checked: completeVM.Eligible " })
        @Html.Label("yes", "YES")
        @Html.RadioButtonFor(model => model.Eligible, "false", new {id="no", data_bind = "checked: completeVM.Eligible " })
        @Html.Label("no", "No")
</div>

如果我不使用 data_bind,当页面加载时,“否”单选按钮将默认设置。但是在我添加 data_bind 之后,两个单选按钮都没有被选中。我注意到在我的视图模型中,Eligible 显示为:"Eligible": false;如果我选中“否”按钮,它将显示为“合格”:“假”。我该如何解决这个问题,以便在页面加载时,默认情况下会选中“否”按钮。谢谢

【问题讨论】:

    标签: asp.net-mvc knockout.js radio-button


    【解决方案1】:

    这是一个常见问题。单选按钮值始终是一个字符串。然而你想要布尔行为。最简单的解决方法是使用额外的计算 observable 为您进行翻译:

    假设“this”指向您的视图模型:

    this.EligibleRadioHelper = ko.computed({
        read: function () {
            return this.Eligible().toString();
        },
        write: function (value) {
            this.Eligible(value === 'true');
        },
        owner: this
    });
    

    绑定这个新的助手:

    data-bind="checked: completeVM.EligibleRadioHelper"
    

    当您想要布尔值(用于逻辑或持久化)时,请使用您原来的 observable。

    【讨论】:

    • 感谢您的快速回答。完美运行:)
    【解决方案2】:

    您也可以尝试使用淘汰赛 3 中提供的 checkedValue 绑定,而无需为您的视图模型编写计算函数。 你的代码会变成这样:

    <div>
       @Html.LabelFor(model => model.Eligible)
        @Html.RadioButtonFor(model => model.Eligible,"true", new { id="yes", data_bind =       "checked: completeVM.Eligible, checkedValue: true" })
        @Html.Label("yes", "YES")
        @Html.RadioButtonFor(model => model.Eligible, "false", new {id="no", data_bind = "checked: completeVM.Eligible, checkedValue: false " })
        @Html.Label("no", "No")
    

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2014-09-24
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多