0

我正在尝试制作一个简化的视图模型,我可以根据它动态生成一些 html。但是,我不太了解如何(或者是否有可能)创建具有动态值的视图模型。

我的视图模型:

public class DataGridViewModel<T>
{
    public List<T> DataList { get; set; }
    public List<HeaderValue> DataHeaders { get; set; }

    public DataGridViewModel(List<T> dataIn)
    {
        DataList = dataIn;
        SetHeaders();
    } 

    public void SetHeaders()
    {
        //Build a list of column headers based on [Display] attribute
        DataHeaders = new List<HeaderValue>();
        var t = DataList.First().GetType();
        foreach (var prop in t.GetProperties())
        {
            var gridattr = prop.GetCustomAttributes(false).FirstOrDefault(x => x is DisplayAttribute);
            var head = gridattr == null ? "" : (string) gridattr.GetType().GetProperty("Name").GetValue(gridattr);
            var visible = gridattr != null;
            DataHeaders.Add(new HeaderValue()
            {
                Header  = head,
                Visible = visible,
                Property = prop.Name
            });
        }
    }
}

我的控制器:

var docdto = DocumentService.FetchDocuments(); //Returns IQueryable<DocumentDTO>
var vm = new DataGridViewModel<DocumentDto>(docdto.ToList());
return View(vm);

文档DTO:

public class DocumentDto
    {
        public Int32 DocumentId { get; set; }

        [Display(Name = "Category")]
        public string CategoryName { get; set; }
    }
//These could be very different, based on the table they're modeled after.

看法:

@model DataGridViewModel<T>

@foreach(var header in Model.DataHeaders)
    {
        <h1>@header.Property</h1>
    }

我遇到的问题是,视图似乎不能使用通用或动态值,并且必须分配给基类。那么问题是DTO都非常不同。

这可能与Razor有关吗?

感谢您的时间 :)

4

0 回答 0