简体   繁体   English

有没有一种方法可以在没有eg的情况下绑定单个项目。 中继器控制?

[英]Is there a way to data bind a single item without eg. a Repeater control?

Lets say I have a single object of type Car which I want to render as HTML: 假设我有一个类型为Car的对象,我想将其呈现为HTML:

class Car {
  public int Wheels { get; set; }
  public string Model { get; set; }
}

I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. 我不想使用ASP.NET Repeater或ListView控件进行绑定,因为它看起来太冗长了。 I just have the one object. 我只有一个对象。 But I still want to be able to use the databinding syntax so I won't have to use Labels or Literals. 但我仍然希望能够使用数据绑定语法,因此我不必使用标签或文字。 Something like: 就像是:

<div>
  Wheels: <%# (int)Eval("Wheels") %><br />
  Model: <%# (string)Eval("Model") %>
</div>

Does anybody know about a control out there that does just that? 有没有人知道那里的控制权呢?

And I am not ready to switch to ASP.NET MVC just yet. 我还没准备好切换到ASP.NET MVC。


Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. 不幸的是,DetailsView控件不能满足我的需求,因为它似乎不支持我所追求的模板式语法。 It, too, needs to be bound to a DataSource object of a kind. 它也需要绑定到某种类型的DataSource对象。

I liked better the solution Maxim and Torkel suggested. 我更喜欢Maxim和Torkel建议的解决方案。 I will try to go for that. 我会尽力去做。

if the page is about a specific item (For exemple, Car.aspx?CarID=ABC123), I normally have a public property on the page called "CurrentCar" 如果页面是关于特定项目(例如,Car.aspx?CarID = ABC123),我通常在名为“CurrentCar”的页面上有一个公共属性

public Car CurrentCar { get; set; }

And I can then have the following: 然后我可以得到以下内容:

<div>
  Wheels: <%= CurrentCar.Wheels %><br />
  Model: <%= CurrentCar.Model %>
</div>

That allow you to have type safety. 这样可以让你有类型安全。 Just make sure to have a valid object assigned before the actual rendering. 只需确保在实际渲染之前分配有效对象。

I would suggest you make car a protected property on the page, this will allow you to access it directly in the aspx page: 我建议您在页面上将汽车设为受保护的属性,这将允许您直接在aspx页面中访问它:

<div>
  Wheels: <%= Car.Wheels %>
  Wheels: <%= Car.Models %>
</div>

This approach is actually better for single item databinding scenarios as the "binding" is strongly typed. 对于单项数据绑定方案,这种方法实际上更好,因为“绑定”是强类型的。

One drawback of the protected property solution is that you cannot use it to bind to properties of controls. 受保护的属性解决方案的一个缺点是您无法使用它来绑定控件的属性。

For example, the following would not work: 例如,以下内容不起作用:

<asp:Label ID="Label1" Text="Probably a truck" Visible='<%# CurrentCart.Wheels > 4 %>' runat="server" />

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

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