問候的StackOverflow,ASP.NET動態數據:使用列名
TL從FormView控件查找DynamicControl的數據控制; DR
在現場模板控件的OnLoad方法我怎麼能找到其他領域的數據控制在FormView的屬性或列名稱中。
END TL; DR。
我想添加一些邏輯到Boolean_Edit字段模板,以便如果綁定到它的屬性有一個新的屬性,我讓模板將注入JavaScript。 JavaScript旨在禁用屬性的ControlledFieldNames
屬性中列出的列/屬性名稱的所有數據控件。
這有點令人困惑,所以我會分享一些代碼。
這裏是屬性類我這個做:
/// <summary>
/// Attribute used to insert javascript into an ASP.NET web page that uses Dynamic Controls so that if the field's value changes it disables (or enables)
/// other web controls on the page which correspond to the other bound property names.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class InputRestrictorFieldAttribute : Attribute
{
public Boolean TargetEnabledState { get; set; }
public String[] ControlledFieldNames { get; set; }
public InputRestrictorFieldAttribute(Boolean targetEnabledState, params String[] controlledFieldNames)
{
this.TargetEnabledState = targetEnabledState;
this.ControlledFieldNames = controlledFieldNames;
}
}
,所以我可能有一個屬性在一些腳手架類,像這樣:
[ScaffoledTable(true)]
public class Person
{
/* Other properties... */
[InputRestrictorFieldAttribute(false, new String[]
{
"StreetAddress",
"City",
"State",
"Zip"
})]
public Boolean AddressUnknown { get; set; }
public String SteetAddress { get; set; }
public String City { get; set; }
public String State { get; set; }
public String Zip { get; set; }
/* some more code */
}
在Boolean_Edit.ascx.cs文件
現在我正在嘗試檢查當前腳手架屬性是否具有InputRestrictorFieldAttribute
,如果是這樣,則將JavaScript注入頁面,以便當AddressUnknown
CheckBox控件被禁用時,TextBox控件爲StreetAddress
,City
,State
和Zip
。
下面是我最近嘗試過的。
protected override void OnLoad(EventArgs e)
{
var attributes = this.Column.Attributes;
foreach (Attribute attr in attributes)
{
if (attr is InputRestrictorFieldAttribute)
{
InputRestrictorFieldAttribute restrictor = (InputRestrictorFieldAttribute)attr;
String restrictorScriptFunctionName = String.Format(RESTRICTOR_SCRIPT_FUNCTION_NAME, ClientID);
String restrictorScript = String.Format(RESTRICTOR_SCRIPT_TEMPLATE_ONCLICK,
restrictorScriptFunctionName,
restrictor.BoundFieldNames.Aggregate("", (aggr, item) =>
{
var bc = this.NamingContainer.BindingContainer;
var ctrl = bc.FindFieldTemplate(item);
return aggr + String.Format(RESTRICTOR_SCRIPT_TEMPLATE_ELEMENT, ctrl.ClientID);
}));
Page.ClientScript.RegisterStartupScript(Page.GetType(), "restrictorScript_" + ClientID, restrictorScript, true);
CheckBox1.Attributes.Add("onchange", restrictorScriptFunctionName + "(this);");
}
}
base.OnLoad(e);
}
現在我知道做這樣的事情讓其他頁面,但對於現在的許多this.NamingContainer.BindingContainer
沒有(或可能不會)工作(在Insert.aspx頁面模板的情況下)的作品。 this.NamingContainer.BindingContainer
是控制Insert.aspx頁面的FormView1
。但是到目前爲止我試圖獲取各種數據的控件或字段模板,或者通過動態控件的屬性名稱,它總是返回null或拋出異常。
最後,聚合方法只是將多個JavaScript連接在一起,以便僅使用一個JavaScript函數停用所有控件。這些腳本的內容對這個問題並不重要。