2011-01-27 123 views
4

我有我的看法文本框,下拉列表等所有這些的幾個要素有這樣的Asp.net MVC動態HTML屬性

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList<MyType>(),new { @class = "someclass", @someattrt = "someattrt"})%> 

創造了一些獨特的屬性,我想創建一個只讀版本的我通過設置另一個屬性禁用。

有誰知道我該如何使用可以在全局範圍內設置的變量來實現它?

喜歡的東西:

If(pageReadOnly){ 
isReadOnlyAttr = @disabled = "disabled"; 
}else 
{ 
isReadOnlyAttr =」」 
} 

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList<MyType>(),new { @class = "someclass", @someattrt = "someattrt",isReadOnlyAttr})%> 

我不想,如果你使用JavaScript來做到這一點

回答

5

我認爲我已經做了類似於你的事情 - 基本上我有幾個不同的用戶該系統和一套在網站上擁有隻讀權限。爲了做到這一點,我對每個視圖模型中的變量:

public bool Readonly { get; set; } 

這取決於他們的角色權限設置在我的模型/業務邏輯層。

我然後創建一個擴展DropDownListFor HTML輔助接受boolean值,指示是否在下拉列表中只應閱讀:

using System; 
using System.Collections.Generic; 
using System.Linq.Expressions; 
using System.Web.Mvc; 
using System.Web.Mvc.Html; 

public static class DropDownListForHelper 
{ 
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> dropdownItems, bool disabled) 
    { 
     object htmlAttributes = null; 

     if(disabled) 
     { 
      htmlAttributes = new {@disabled = "true"}; 
     } 

     return htmlHelper.DropDownListFor<TModel, TProperty>(expression, dropdownItems, htmlAttributes); 
    } 
} 

注意,您可以創建能夠利用多個參數還包括其他實例。

比在我看來,我只是進口的命名空間爲我的HTML輔助擴展名,然後在視圖模型變量傳遞只讀到DropDownListFor HTML輔助:

<%@ Import Namespace="MvcApplication1.Helpers.HtmlHelpers" %> 

<%= Html.DropDownListFor(model => model.MyDropDown, Model.MyDropDownSelectList, Model.Readonly)%> 

我爲TextBoxFor,TextAreaFor和CheckBoxFor相同他們似乎都工作得很好。希望這可以幫助。

4

而不要禁用下拉列表,爲什麼不能取代它與所選擇的選項...在這樣做了很多的東西,你應該想想有一個只讀視圖和編輯視圖...

<% if (Model.IsReadOnly) { %> 
    <%= Model.MyModel.MyType %> 
<% } else { %> 
    <%= Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList<MyType>(),new { @class = "someclass", someattrt = "someattrt"})%> 
<% } %> 

而且正如順便說一句,你只需要轉義「的屬性名@ 「如果它是保留字,比如」class「。

更新

好。我的確有一個答案 - 但條件是你在實施之前閱讀這些內容。

MVC是關於分離問題。將邏輯放在控制器中,特別是該視圖的關注點是濫用MVC。請不要這樣做。任何特定於視圖的東西,比如HTML,屬性,佈局 - 這些都不應該在「controllerville」中表現出來。控制器不應該改變,因爲你想改變視圖中的某些東西。

瞭解MVC試圖實現的內容以及下面的示例會打破整個模式並將視圖放在應用程序中的錯誤位置非常重要。

正確的修復方法是擁有「讀取」視圖和「編輯」視圖 - 或者將任何條件邏輯放入視圖中。但這是一種做你想做的事情的方式。 。:(

這個屬性添加到模型

public IDictionary<string, object> Attributes { get; set; } 

在控制器,你可以有條件地設置屬性:

model.Attributes = new Dictionary<string, object>(); 
model.Attributes.Add(@"class", "test"); 
if (isDisabled) { 
    model.Attributes.Add("disabled", "true"); 
} 

使用您的視圖屬性:

<%= Html.TextBoxFor(model => model.SomeValue, Model.Attributes)%> 
+0

這個視圖有很多東西,我們只需要它就可以做某種「演示」。 我試圖避免在每個元素上創建一個單獨的視圖或放置「if」語句。我寧願從表單中刪除提交按鈕並添加禁用的屬性。那可能嗎 ? – Bart 2011-01-27 12:05:13

+0

我已經添加了一個這樣的例子。只是因爲這可能並不意味着你必須這樣做...請閱讀上面的例子。 – Fenton 2011-01-27 13:53:39