私は、それに基づいていくつかの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で行うことができますか?
お時間をいただきありがとうございます:)