我正在基於實體框架的Web UI上進行數據操作。ASP.NET強制動態生成的控件被視爲新的
假設我有以下兩種模式:
public class Bottle
{
[Key]
public Int32 BottleId { get; set; }
[Required]
[MinLength(3)]
[MaxLength(128)]
public String Name { get; set; }
[Required]
public virtual BottleType BottleType { get; set; }
}
public class BottleType
{
[Key]
public Int32 BottleTypeId { get; set; }
[Required]
[MinLength(3)]
[MaxLength(128)]
public String Name { get; set; }
public virtual ICollection<Bottle> Bottles { get; set; }
}
這些模型可能值將
Bottle {
Name = "Foo"
BottleType = BottleType {
Name = "Unicorn Bottle"
}
}
Web UI中會顯示一個下拉列表有兩個項目,一個用於Bottle
和一個爲BottleType
。如果選擇更改,則會根據模型的屬性生成新控件。
作爲例子,如果選擇Bottle
,6個控制將生成 - 3個標籤和3個輸入框:
- 標籤,文本= 「BottleId」
- 文本框禁用,文本=「(自動) 「 - 因爲它的價值會在數據庫中自動生成
- 標籤,文本= 」名稱「
- 文本
- ...
也,mandatory
將適用於每個控件的標籤,如果需要輸入。
現在談論我的問題;當我更改下拉菜單的選定索引時,控件將被刪除,其中panel.controls.clear()
。之後將爲選定的模型生成新控件。
我不確定問題的原因是什麼,它可能是控件在頁面上的「位置」,導致asp.net將其視爲「相同」。
這裏是第2行之後的代碼剪斷
1 | Panel p = new Panel();
2 | Label l = new Label
3 | {
4 | Text = "bar" // this would be the name of the property
5 | };
6 | p.Controls.Add(l);
7 | if (... required check ...)
8 | {
9 | // is required
10 | l.Text += " (mandatory)";
11 | }
,l.Text
等於bar
(像它應該是)。但是,如果之前的模型具有同名的屬性,它將在第6行之後將l.Text
的值更改爲bar (mandatory)
(這是之前模型的標籤的值),然後將導致第10行之後的bar (mandatory) (mandatory)
。
長話短說:我可以強制asp.net將生成的控件視爲新對象嗎?
我試着給每個標籤生成一個唯一的標識,用Guid.NewGuid().ToString()
表示不同的實例,但這似乎不起作用。
我在這個主題上找不到任何相關的問題,因爲大多數時候人們想要重新生成控件並保留它們的值,但是不是在我的情況下。