如何使用foreach將我的屬性從模型導入到我的視圖中?如何使用foreach將我的屬性從模型導入到我的視圖中?
我知道我可以使用@Html.EditorFor(model => model.ID)
但在我的情況下,這是不可能的,因爲我使用一個視圖爲不同的模型(從BaseModel繼承)。
型號:
public class MyModel : IEnumerable
{
private PropertyInfo[] propertys
{
get
{
if (propertys != null) return propertys;
string projectName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Type classtype = Type.GetType(string.Format("{0}.Models.{1}", projectName, FQModelname));
PropertyInfo[] properties = classtype.GetProperties();
return properties;
}
}
public int ID { get; set; }
public string Name { get; set; }
//...
public IEnumerator GetEnumerator()
{
return propertys.GetEnumerator();
}
}
RazorView:
@foreach (var property in Model)
{
// [Error] need Typeargument...?
@Html.EditorFor(property);
}
製作您的基本抽象,並強制您的模型類實現某種類型的對象屬性[index]運算符或方法,並在視圖中調用它。 – asawyer
聽起來不錯,你能舉個例子嗎? – jwillmer
當然,現在發佈。 – asawyer