ASP.NET MVC3 @Html.EditorFor 复选框禁用启用

6

我是一名使用Razor的ASP.NET MVC3开发人员。我遇到了这样的情况:基于一个布尔属性,我想要启用或禁用一个复选框。我的模型类有两个属性:

public bool IsInstructor { get; set; }
public bool MoreInstructorsAllowed { get; set; }

现在,在我的cshtml文件中,我将复选框显示为:
@Html.EditorFor(model => model.IsInstructor)

我希望这个复选框可以根据MoreInstructorsAllowed属性启用或禁用。 感谢您提前提供解决方案。 :)

我在http://stackoverflow.com/questions/6590663/make-checkbox-disabled-in-asp-net-mvc-2-and-jquery看到了一个解决方案,但我想使用EditorFor而不是CheckBoxFor。 - Imran Balouch
2个回答

4
EditorFor扩展方法将您的Model与位于EditorTemplates文件中的PartialView连接起来,该PartialView对应于Model的类型(因此在这种情况下,它需要是Boolean.cshtml)。
您可以通过向Editor模板添加条件逻辑来实现您的目标。您还需要为Partial视图提供一种知道MoreInstructorsAllowed属性值的方式,并使用带有additionalViewData参数的EditorFor重载来传递此信息。
说实话,更改处理布尔值的默认功能似乎对您要做的事情来说有些过度了。如果这两个字段在本质上是相关联的,那么将这两个字段组合起来并将一个Partial视图连接到组合而不是连接到布尔值本身会更有意义。我的意思是:
public class InstructorProperty { 
    public bool IsInstructor { get; set; }
    public bool MoreInstructorsAllowed { get; set; }
}

并且在 /Shared/EditorTemplates/InstructorProperty.cshtml

@model InstructorProperty

//  ...  Your view logic w/ the @if(MoreInstructorsClause) here.

唯一的问题是,现在您又回到了必须使用CheckboxFor方法才能应用“disabled”属性的问题,因为EditorFor方法不接受即席html属性。已知的解决方法涉及覆盖您的ModelMetadataProvider并使用您提供处理的属性装饰该属性。此技术的工作示例可在以下网址找到:http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx。但是,这仍然需要:(1)覆盖布尔视图并在其中硬编码html或使用CheckboxFor,(2)在InstructorProperty视图中使用CheckboxFor方法,或者(3)将html硬编码到InstructorProperty视图中。我认为为了这么微不足道的事情而过分复杂化设计没有意义,因此我的解决方案是在这个InstructorProperty视图中添加:
@Html.CheckboxFor(_=>_.IsInstructor, 
    htmlAttributes: (Model.MoreInstructorsAllowed ? null : new { disabled = "disabled"} ).ToString().ToLowerInvariant() });        

但我明白每个人的风格都不同... 另外一个小提示是,如果你不想使用复选框方法是因为生成的命名方案,那么 Mvc 框架访问此功能的方式涉及 html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)


非常感谢您提供的详细回复,但如果我们使用CheckboxFor,那么MoreInstructorsAllowed属性将必须是字符串吗?因为disabled属性不能是true或false,它可以是禁用和启用。 - Imran Balouch

-1
@if (Model.MoreInstructorsAllowed) 
  { 
//if MoreInstructorsAllowed true then checkbox IsInstructor not disabled
    @Html.EditorFor(model => model.IsInstructor)
  }
  else
  {
//else MoreInstructorsAllowed false then checkbox IsInstructor will disabled
    @Html.EditorFor(model => model.IsInstructor, new { htmlAttributes = new { @disabled = "disabled" } })
  }

感谢您提供答案。您是否可以编辑您的答案并包含代码解释?这将有助于未来的读者更好地理解正在发生的事情,特别是那些对该语言感到陌生并且难以理解概念的社区成员。当已经有一个被社区验证的已接受答案时,这尤其重要。在什么条件下可能会优先考虑您的方法?您是否利用了新的功能? - Jeremy Caney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接