Как я могу получить свои свойства из модели в моем представлении с foreach? - PullRequest
1 голос
/ 27 июня 2011

Как я могу получить свои свойства из модели в свой вид с помощью 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);
}

Ответы [ 2 ]

1 голос
/ 27 июня 2011

Вы пробовали @Html.EditorForModel() вместо @Html.EditorFor() ??

0 голосов
/ 27 июня 2011

Это можно было бы сделать более строгим шрифтом, но, по крайней мере, это быстрая реализация идеи, вам нужно уточнить некоторые концепции и получить что-то работающее для вашего конкретного проекта.

void Main()
{
    BaseModel baseModelTest = new Concrete() { Test = "test property" };

    foreach ( var property in baseModelTest.EnumerateProperties())
    {
        var value = baseModelTest.GetPropertyValue(property.Name);
        value.Dump();
    }


}

public class EnumeratedProperty
{
    public string Name { get; private set; }
    public Type Type { get; private set; }
    public EnumeratedProperty(string PropertyName, Type PropertyType)
    {
        this.Name = PropertyName;
        this.Type = PropertyType;
    }
}

public abstract class BaseModel
{
    protected IEnumerable<PropertyInfo> PropertyInfoCache { get; set; }
    protected IEnumerable<EnumeratedProperty> EnumeratedPropertyCache { get; set; }
    protected BaseModel()
    {
        PropertyInfoCache = this.GetType().GetProperties();
        EnumeratedPropertyCache = PropertyInfoCache.Select(p=> new EnumeratedProperty(p.Name,p.GetType()));
    }
    public IEnumerable<EnumeratedProperty> EnumerateProperties()
    {
        return EnumeratedPropertyCache;
    }
    public object GetPropertyValue(string PropertyName)
    {
        var property = PropertyInfoCache.SingleOrDefault(i=>i.Name==PropertyName);
        if(property!=null)
            return property.GetValue(this,null);
        return null;
    }
}

public class Concrete : BaseModel
{
    public string Test { get; set; }
}

....

public static class ExtensionMethods
{
    public static MvcHtmlString EditorForProperty(this HtmlHelper html, BaseModel Model, EnumeratedProperty property)
    {
        // invoke the appropriate Html.EditorFor(...) method at runtime
        // using the type info availible in property.Type
        return ...
    }
}

....

@foreach (var property in Model.EnumerateProperties())
{
    // call the new extention method, pass the EnumeratedProperty type
    // and the model reference
    @Html.EditorForProperty(Model,property);
}
...