2012-06-06 151 views
5

我正在使用Razor在ASP.NET MVC3中工作。我有一種情況,我想啓用禁用基於布爾屬性的複選框。我的模型類有2個屬性,如:ASP.NET MVC3 @ Html.EditorFor複選框禁用啓用

public bool IsInstructor { get; set; } 
public bool MoreInstructorsAllowed { get; set; } 
我CSHTML文件

現在,我表示作爲複選框:

@Html.EditorFor(model => model.IsInstructor) 

我想這個複選框啓用禁用MoreInstructorsAllowed財產的基礎。 預先感謝解決方案。 :)

+0

我在http://stackoverflow.com/questions/6590663/make-checkbox上看到了一個解決方案-disabled-in-asp-net-mvc-2-and-jquery但我想用EditorFor代替CheckBoxFor –

回答

3

EditorFor擴展方法將您的模型連接到位於與模型類型相對應的EditorTemplates文件中的PartialView(因此在這種情況下,它將需要爲Boolean.cshtml)。

您可以通過向編輯器模板添加條件邏輯來實現您的目標。您還需要給出部分方法來知道MoreInstructorsAllowed屬性的值,並且您可以使用EditorFor過載和additionalViewData參數來傳遞此信息。

老實說,改變處理布爾值的默認功能看起來就像是你想要做的事情。如果這兩個領域有根本的聯繫,那麼將這兩個領域組合起來並將局部視圖連接到組合而不是布爾人本身會更有意義。我的意思是:

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方法的問題爲了應用「禁用」屬性,因爲EditorFor方法不接受ad hoc 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)在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)

+0

非常感謝這個詳細的回覆,但是如果我們使用CheckboxFor,那麼比MoreInstructorsAllowed屬性將不得不是字符串?由於禁用的屬性不能爲真或假,可以禁用並啓用它。 –

+0

這是正確的。我修改了我的答案。 – smartcaveman