如何禁用我的@Html.ListBoxFor()

How do I disable my @Html.ListBoxFor()

我需要能够根据审核状态禁用此 ListBoxFor()。尽管下面的代码有效,但它显示了所有列表项。

@Html.ListBoxFor(m => m.ListOptions, filetypes, Model.IsUnderReview ? new { @class = "disabled" } : new { @class = "multiselectFileTypes" })

禁用它的语法是什么,只是为了显示“已选择 2 个项目”?

您不能对 htmlAttributes 参数进行内联条件检查。

这应该有效。

@using (Html.BeginForm())
{
  <label>Select something </label>
  if (!Model.IsUnderReview )
  {
    @Html.ListBoxFor(m => m.ListOptions, filetypes, new { @class = "multiselectFileTypes"})
  }
  else
  {
    @Html.ListBoxFor(m => m.ListOptions, filetypes, new { disabled = "disabled" })
  }
}

看来答案是使用 Html.helper 命令 HiddenFor(),像这样

@if (Model.IsUnderReview)
{
    //You then need to generate a hidden input for each value in SelectedRoles, as it's an array
    @Html.HiddenFor(m => m.SelectedRoles) 
}
else
{
    @Html.ListBoxFor(x => x.SelectedRoles, filetypes, new { @class = "multiselectFileTypes" , id = "staticFieldM_" + Model.ID})
}

通过为每个 SelectedRole 项目创建一个隐藏输入,然后禁用整个列表。