【问题标题】:Set @Html.RadioButtonFor as Checked by default将@Html.RadioButtonFor 设置为默认选中
【发布时间】:2012-09-08 09:19:39
【问题描述】:

我无法将默认单选按钮设置为“已选中”! 我正在使用@Html.RadioButtonFor :

<div id="private-user">
    @Html.RadioButtonFor(m => m.UserType, "type1", new { @class="type-radio" , **@Checked="checked"** }) 1
</div>
<div id="proff-user">
    @Html.RadioButtonFor(m => m.UserType, "type2", new { @class="type-radio" }) 2
</div>

是否可以使用 @Html.RadioButtonFor 将单选按钮设置为 cheched ?

谢谢

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor radiobuttonfor


    【解决方案1】:

    【讨论】:

    • 即使在我的例子中,UserType 是一个“枚举”。我应该将它转换为封装枚举 UserType 的其他类型的对象吗?
    【解决方案2】:

    看看这篇文章,他们已经回答了你的问题(尽管是 MVC 2,但在这种情况下是一样的):

    How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      在您的控制器操作中,将视图模型上的 UserType 属性的值设置为相应的值:

      public ActionResult SomeAction()
      {
          MyViewModel model = ...
      
          // preselect the second radio button
          model.UserType = "type2";
          return View(model);
      }
      

      在你看来:

      <div id="private-user">
          @Html.RadioButtonFor(m => m.UserType, "type1", new { @class="type-radio" }) 1
      </div>
      <div id="proff-user">
          @Html.RadioButtonFor(m => m.UserType, "type2", new { @class="type-radio" }) 2
      </div>
      

      【讨论】:

        【解决方案4】:

        在 View Model 的构造函数中,只需将属性初始化为所需的值即可。

        public YourViewModel(){
            UserType = "type1";
        }
        

        这样您的回发将使用您想要的任何值,而您不必在控制器中设置值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-28
          • 2017-04-28
          相关资源
          最近更新 更多