简体   繁体   English

从列表C#asp.net填写表格

[英]Fill a table from a list C# asp.net

I have a class Car , with some atributtes Model and Year . 我上课有Car ,有一些ModelYear I have a list ( List<Car> carList = new List<Car>() ) of some objects of the class Car , and I want to put this list into an HTML tag , but I have no idea how to do this. 我有一个名单( List<Car> carList = new List<Car>()之类的一些对象的Car ,我希望把这个列表插入到HTML标记,但我不知道如何做到这一点。

I got a template that already has a <table> , that's why I'm trying to use <table> instead of <asp:GridView> . 我有一个已经有<table>的模板,这就是为什么我尝试使用<table>而不是<asp:GridView>

I'm using WebForms 我正在使用WebForms

If you are set on using a <table> and not any of the <asp:*> controls, you can manually build your markup on the page. 如果设置为使用<table>而不使用任何<asp:*>控件,则可以在页面上手动构建标记。

First, you need to be able to access the object from your markup. 首先,您需要能够从标记访问对象。 By making it a protected (or public ) property on the code-behind, the page can access it: 通过在后面的代码中将其设置为protected (或public )属性,页面可以访问它:

protected IList<Car> CarList { get { return carList; } }

Then in the page (which inherits from the code-behind class) you can access that property to build markup. 然后,在页面(继承自代码隐藏类)中,您可以访问该属性以构建标记。 Something like this: 像这样:

<% foreach (var car in CarList) { %>

<% } %>

Inside of that loop would be your rows, outside would be your table dressing. 该循环的内部将是您的行,外部将是您的餐桌装饰。 Something like this, perhaps: 大概是这样的:

<table>
  <tr>
    <th>Column Heading</th>
  </tr>
<% foreach (var car in CarList) { %>
  <tr>
    <td><%= car.SomeValue %></td>
  </tr>
<% } %>
</table>

This is similar to how one may construct markup in MVC, so you can think of it like that. 类似于在MVC中构造标记的方式,因此您可以这样想。 Though it's not common for WebForms and it's often recommended to use the framework the way it's meant to be used. 尽管对于WebForms来说并不常见,并且通常建议按其使用方式使用该框架。 In the long run, if you're set on using WebForms, it may be less work to adjust the template to work with the server-side controls than to manually build the markup. 从长远来看,如果您打算使用WebForms,则调整模板以使其与服务器端控件一起使用可能比手工构建标记要少。 The server-side controls have the added benefit of lots of event binding and code-behind interactions. 服务器端控件具有许多事件绑定和代码隐藏交互的附加好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM