开发者

In ASP.net MVC , how to use a dynamic model?

I create model from my sql 2008 server database using northwind example. Model.Order, I w开发者_开发知识库ant to dynamically use the Order rows, just like datatable

DataTable a = New DataTable() .

.......fill the order data to table a .and then I can use

a[1] or a["orderid"] to get the data . but in mvc Ican just use Model.Order a = new Model.Order() ...fill the a with data . use a.OrderID to get the data

Is there any way to foreach it with count like

 for(int i=0;i<a.count;i++)
    {
      //how to get the data like these way ??
    } 


Generally speaking you want to give your View an IEnumerable<T>. So for example, you do something like:

@model IEnumerable<Project.WebUI.Models.Order>

@foreach (var item in Model) {
    <h1>item.Customername</h1>
}

In your controller, you have to create an IEnumerable<Order> collection and then pass it along the view. Since the controller is just a C# class, creating the collection will be the same process as you've come to know during previous .NET work.

The only new thing that you have to realize in MVC is that the View is dumb. It doesn't do any code processing, just burps up the information you've given it from the controller into a format you've defined in the view.

Does this make sense?


This answer should answer your question

Enumerating through an object's properties (string) in C#

with Model.GetProperties() in get a list of all the properties. Then with a foreach you obtain the names and values of them. Hope it helps


From your replies above it sounds like you want to use the ModelMetadata to display the data for an unknown model type. I developed Dynamic MVC to do something like this. Let me know if this helps.

http://dynamicmvc.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜