简体   繁体   English

常规ASP.NET 4.0 aspx页(不是MVC)中的代码块

[英]Code blocks in regular ASP.NET 4.0 aspx pages (not MVC)

Is it possible to do something like this in regular ASP.NET (or something similar): 是否可以在常规ASP.NET中执行以下操作(或类似操作):

<ul>
    <% foreach (var item in Model) { %>       
        <li id="<%: item.Id %>">    
            blah blah     
        </li>       
    <% } %>
</ul>    

I need to do a gird, but I want to control how the html table is output. 我需要做一个网格,但是我想控制html表的输出方式。

Yes, the code written this way behaves as if it was written in code behind. 是的,以这种方式编写的代码的行为就像是在后面的代码中编写的一样。 If you want to have both, that works too. 如果您想同时拥有两者,那也可以。 Expose a property in the page code behind class that is the Model and then you can access it the way you have shown. 在类后面的页面代码中公开一个属性,即Model,然后可以按照显示的方式访问它。

public partial class _Default : System.Web.UI.Page
{
    protected List<WhateverClass> Model { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Populate the model here or in another appropriate event
    }
}

It is possible since MVC just uses the ASP.NET rendering engine (where the <% server tags come from). 因为MVC仅使用ASP.NET呈现引擎(<%服务器标记来自哪里),所以这是可能的。 However, you should probably use the repeater control as @Eric mentioned. 但是,您应该使用@Eric提到的转发器控件。 The problem is that the Model may not be initialized at the time your page is compiled and you are likely to get a null reference exception. 问题在于,在编译页面时可能无法初始化模型,并且您很可能会得到空引用异常。

Yes, you can do it, but when in web forms you should probably do things the "web forms way" (or else why use web forms). 是的,您可以执行此操作,但是在Web表单中时,您可能应该使用“ Web表单方式”(否则,为什么要使用Web表单)。

In your example you can accomplish the same thing with a repeater. 在您的示例中,您可以使用中继器完成相同的操作。

Note that this stylistic advice; 请注意,这种风格建议; both approaches are 100% correct. 两种方法都是100%正确的。

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

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