Reputation: 18257
I Have a View stronger Typed, of my class called Cliente
, Defined like this
public partial class Cliente
{
public Cliente()
{
this.Campana = new HashSet<Campana>();
}
public short IdCliente { get; set; }
public short IdDireccion { get; set; }
public string Descripcion { get; set; }
public bool Activo { get; set; }
public virtual ICollection<Campana> Campana { get; set; }
public virtual Direccion Direccion { get; set; }
}
I want to add The elements of the class Campana, so I passed into my viewBag like this
ViewBag.Campanas = db.Campana;
Now what I want to know, it's how can i Made a lambda expression to create labels, and fields based on the class. I tried like this but It doesn't work
@foreach (var item in ViewBag.Campanas)
{
@Html.LabelFor (modelItem => item.Descripcion)
}
Here's the Campana Class
public partial class Campana
{
public Campana()
{
this.Servicio = new HashSet<Servicio>();
}
public short IdCampana { get; set; }
public short IdCliente { get; set; }
public string Descripcion { get; set; }
public bool Activo { get; set; }
public virtual Cliente Cliente { get; set; }
public virtual ICollection<Servicio> Servicio { get; set; }
}
Upvotes: 1
Views: 470
Reputation: 1039438
Now what I want to know, it's how can i Made a lambda expression to create labels, and fields based on the class
You can totally forget about lambdas and strong typing if you use this crap of ViewBag/ViewData. Not a chance. ViewBag is dynamic resolution that doesn't provide any compile-time type safety.
I would recommend you using view models and having your controller actions pass specific view model types to your views. Simply forget about the existence of ViewBag. It will make your code strongly typed and compile-time safe.
There are so much articles and tutorials over the www teaching people this cancer of ViewBag
. I am really sick of it. Please don't ever use it in any of your applications.
@model MyViewModel
)Conclusion: it's only once you have completely removed any trace of ViewBag/ViewData from your application we can talk about lambdas and strong typing in your views.
Upvotes: 3
Reputation: 77606
The reason you're getting that error is because you can't use lambdas on dynamic
references. (i.e. ViewBag
) Now, you've said something about strongly typed views, but your view isn't actually strongly typed. To do that, you use the @model
directive. You can declare your model like this:
@model Table<Campana>
Then instead of using ViewBag.Campanas
, you can use Model
. Or you could just pass in the whole data context (db
) if you cared to. However, this is not very good practice. It's better to create separate "view models" for your views and translate your linq-to-sql objects into your view models.
Upvotes: 1