Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. 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.


Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.

I liked better the solution Maxim and Torkel suggested. I will try to go for that.

like image 339
JacobE Avatar asked Oct 22 '08 11:10

JacobE


People also ask

What is an example of simple data binding control?

Simple data binding is the type of binding typical for controls such as a TextBox control or Label control, which are controls that typically only display a single value.

Which method activates the binding in repeated value data binding?

Once you specify data binding, you need to activate it. You accomplish this task by calling the DataBind() method (for the control or page).

Which control provides flexible data binding options?

FormView control It allows for a more flexible layout when displaying a single record. The FormView control renders all fields of a single record in a single table row.


2 Answers

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"

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.

like image 189
Maxime Rouiller Avatar answered Oct 05 '22 02:10

Maxime Rouiller


I would suggest you make car a protected property on the page, this will allow you to access it directly in the aspx page:

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

This approach is actually better for single item databinding scenarios as the "binding" is strongly typed.

like image 38
Torkel Avatar answered Oct 05 '22 02:10

Torkel