Imr*_*uch 5 asp.net razor asp.net-mvc-3
我正在使用Razor在ASP.NET MVC3中工作.我有一种情况,我想启用禁用基于布尔属性的复选框.我的模型类有2个属性,如:
public bool IsInstructor { get; set; }
public bool MoreInstructorsAllowed { get; set; }
Run Code Online (Sandbox Code Playgroud)
现在在我的cshtml文件中,我将复选框显示为:
@Html.EditorFor(model => model.IsInstructor)
Run Code Online (Sandbox Code Playgroud)
我希望此复选框在MoreInstructorsAllowed属性的基础上启用禁用.提前感谢您的解决方案.:)
扩展EditorFor
方法将您的模型连接到位于与模型类型相对应的 EditorTemplates 文件中的 PartialView(因此在本例中,它需要是Boolean.cshtml
)。
您可以通过向编辑器模板添加条件逻辑来实现您的目标。您还需要为部分提供一种方法来了解该MoreInstructorsAllowed
属性的值,并且可以使用EditorFor
带有additionalViewData
参数的重载来传递此信息。
老实说,更改处理布尔值的默认功能似乎对于您想要做的事情来说有点太多了。如果这两个字段从根本上联系在一起,那么将这两个字段组合起来并将部分视图连接到组合而不是布尔值本身会更有意义。我的意思是:
public class InstructorProperty {
public bool IsInstructor { get; set; }
public bool MoreInstructorsAllowed { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并在/Shared/EditorTemplates/InstructorProperty.cshtml中
@model InstructorProperty
// ... Your view logic w/ the @if(MoreInstructorsClause) here.
Run Code Online (Sandbox Code Playgroud)
唯一的问题是,现在您又回到了必须使用该CheckboxFor
方法才能应用“禁用”属性的问题,因为这些EditorFor
方法不接受临时 html 属性。有一种已知的解决方法,涉及使用ModelMetadataProvider
您在 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)在视图CheckboxFor
中使用方法InstructorProperty
,或者(3)将 html 硬编码到InstructorProperty
看法。我认为对于这样一件微不足道的事情让设计过于复杂是没有意义的,所以我的解决方案是使用这个InstructorProperty
视图并添加:
@Html.CheckboxFor(_=>_.IsInstructor,
htmlAttributes: (Model.MoreInstructorsAllowed ? null : new { disabled = "disabled"} ).ToString().ToLowerInvariant() });
Run Code Online (Sandbox Code Playgroud)
但我知道每个人都有不同的风格......还有一个旁注。如果您厌恶使用 Checkbox 方法与生成的命名方案有关,那么 Mvc 框架访问此功能的方式涉及html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
归档时间: |
|
查看次数: |
9028 次 |
最近记录: |