【问题标题】:Unable to show selected MVC Radio button无法显示选定的 MVC 单选按钮
【发布时间】:2016-08-08 23:34:53
【问题描述】:

我正在使用 ASP.NET、MVC、Razor 中的 RadioButton 组,并尝试根据先前选择的选项动态设置单选组上的选定按钮。这里是相关的代码sn-p:

List<Product> productList = ViewBag.ProductList;
    if (productList != null && productList.Count > 0)
    {
       foreach (Product product in productList)
       {
            <tr>
                 <td>
                  @Html.RadioButtonFor(p => p.ProductIdString, productList[i].Id, new { Checked = @ViewBag.ProductSelected==product.Id ? true: false, onclick="this.form.submit();", tabindex = @tab })
                  @{tab++;}
                  @{i++;}
                        <td>@product.Name</td>
                        <td>@product.Description</td>
                        <td>@product.FormattedPrice</td>
            </tr>
        }
}

在页面的第一次发布期间,一切都按预期工作。保存的 productId 正确设置了选项。但是,如果在初始加载后选择了一个新选项,那么选中的按钮 Checked 和选中的属性和属性将如图所示正确设置,但之前选中的按钮会在表单上标记为选中:

 <td>
    <input Checked="True" checked="checked" data-val="true" data-val-required="Please select a product" id="ProductIdString" name="ProductIdString" onclick="this.form.submit();" tabindex="30" type="radio" value="1" />
</td>

我已经阅读了很多帖子,其中指出 Checked/checked attributes/properties 用于默​​认选择,并且一旦设置,似乎无法更改?这个对吗?如果没有,您如何动态设置选定的单选按钮?

请注意,当表单提交给控制器时,Request 对象具有正确选择的值,但它只是不显示为选中状态。

我在这里不知所措,如果有任何建议,我将不胜感激。

【问题讨论】:

    标签: javascript c# jquery asp.net


    【解决方案1】:

    我首先要说的是,你在 View 上的逻辑应该首先在 Controller 中解析,并在你将它传递给 viewbag 或模型中的 View 时准备好显示。

    要更改收音机的值,您将需要一些 javascript 或使其更容易使用 jQuery。看看这篇文章:

    https://api.jquery.com/change/

    https://learn.jquery.com/using-jquery-core/faq/how-do-i-check-uncheck-a-checkbox-input-or-radio-button/

    【讨论】:

      【解决方案2】:

      您的代码的问题在于它没有以正确的方式处理 html 属性“已检查”。

      checked 属性是一个布尔属性!如果该属性存在,无论其内容是什么(true、false、checked、foobar),都会选中单选按钮。

      因为在 Razor 元素中很难有一个可选的 html 属性,所以我使用了这个trick

      @Html.RadioButtonFor(p => p.ProductIdString, productList[i].Id, 
      Dictionary<string, object>() {
          {"checked" + (@ViewBag.ProductSelected==product.Id ? "": "not"), ""},
          {"onclick", "this.form.submit();"}, 
          {"tabindex", @tab} 
      })
      

      这样单选按钮元素在未被选中时具有checkednot 属性,而在它们被选中时具有checked 属性。浏览器只是忽略了checkednot属性,只检查了一个元素。

      【讨论】:

        猜你喜欢
        • 2014-03-01
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-06
        • 1970-01-01
        • 2018-06-16
        相关资源
        最近更新 更多