DropDownListFor Helper from generic IEnumerable <T>
I have a project using DDD and MvC3 with a razor in this project, there is one generic Entity class:
public class Entity
{
public long Id{ get; set;}
}
And another class:
public class Categories : Entity
{
public string Name { get; set; }
public string Description { get; set;}
}
and other classes that inherit from categories, Ex:
public class VideoCategory : Categories
{
// no have aditional proprieties
}
You need to create a helper that sets the DropDownList from IEnumerable<Categories>
.
I have a BaseRepository that returns a list of any type, I would use it to speed up.
public abstract class BaseRepository<TEntity> where TEntity: Entity
{
protected DbContext DbContext
{
get
{
return DependencyResolver.Get<IDbContext>() as DbContext;
}
}
public virtual IList<TEntity> GetAll()
{
return ((IEnumerable<TEntity>)this.DbSet).Where(x => x.Deleted == false).OrderByDescending(item => item.Id).ToList();
}
}
and a repository for each object, Ex:
public class VideoRepository : BaseRepository<VideoCategory >
{
}
so i can use the repository in the obeter list in the general class
+3
source to share
1 answer
You can use the view model:
public class MyViewModel
{
public long SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then, assuming you have a set of categories, enter the view model:
public class HomeController : Controller
{
public ActionResult Index()
{
var categories = new[]
{
new Categories { Id = 1, Name = "cat 1" },
new VideoCategory { Id = 2, Name = "cat 2" },
};
var model = new MyViewModel
{
Categories = categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
})
};
return View(model);
}
}
and finally, create an appropriate dropdown in the view:
@model MyViewModel @Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories)
+3
source to share