【问题标题】:Make radio button have a default of what it starts on使单选按钮具有默认启动的内容
【发布时间】:2020-07-08 18:13:00
【问题描述】:

我的模型中声明了一个“PartActionType”,看起来像这样

    public enum PartActionType
    {
        Transfer,
        Harvest,
        Dispose
    }

在我的视图页面中,我使用它来显示 3 个选项

 @foreach (var actionType in partActionTypes)
    {
      <td>
         @Html.RadioButtonFor(x => x.Components[i].SelectedActionType, actionType)
      </td>
    }

在我的示例中,如何使其默认为一个选项我希望“转移”单选框成为默认选项。

这是在采纳 Davids 的建议后发生的事情

【问题讨论】:

  • 我不会编写 razor 代码,但我认为您可以在 for 循环后找到控件并设置 select = true 或编写 javascript 代码会更好

标签: c# html css asp.net-mvc razor


【解决方案1】:

您在初始化视图模型时默认选择的操作类型。永远不要在你的视图中放置很多 if-else 语句。

public ActionResult Index()
{
    var vm = new ItemViewModel
    {
        ItemId = 123,
        ItemName = "Fake Item",
        Components = new List<ItemComponentViewModel>
        {
            new ItemComponentViewModel
            {
                ComponentId = 1,
                ComponentName = "Part 1",
                SelectedActionType = PartActionType.Transfer
            },
            new ItemComponentViewModel
            {
                ComponentId = 2,
                ComponentName = "Part 2",
                SelectedActionType = PartActionType.Transfer
            },
            ...        
        };
    };

    return View(vm);
}

【讨论】:

  • 谢谢!但由于某种原因,它跳过了某些部分而不检查任何内容
  • 如果您从持久性存储中获取数据,您可能需要将任何部分操作类型转换为枚举的逻辑。我刚刚想出了将动作类型作为枚举的想法。您可能不会将它们作为枚举保存在数据库中。
  • 实际上是的,问题又回来了,我将在我的问题中添加一个屏幕截图
  • 我添加了它。正如您所见,大多数值都已检查,但由于某种原因,有些没有
  • 再说一次,我不知道它们是如何存储在您的数据库中的。您可能必须将它们转换为枚举。如果枚举中不存在它们,则必须添加它们。
【解决方案2】:

你可以这样做

foreach (var actionType in partActionTypes)
    {
      if (actionType == PartActionType.Transfer)
      <td>
         @Html.RadioButtonFor(x => x.Components[i].SelectedActionType, actionType, new {@checked="checked"})
      </td>
else
      <td>
         @Html.RadioButtonFor(x => x.Components[i].SelectedActionType, actionType)
      </td>
    }

【讨论】:

  • 谢谢!但是我收到 Operator '==' cannot be applied to operands of type 'object' and 'partActionType' 的错误
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 2017-12-16
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多