I want to create a SelectList Dropdown in MVC.
I prefer select list to be in repository, not in controller. How do I call a repository, without even referring to the nam
Your current GetAllLookupKey
would not compile! Use this version.
public IEnumerable<SelectListItem> GetAllLookupKey()
{
return _context.ProductType.Select( pt=>new SelectListItem
{
Value = pt.ProductTypeName,
Text = pt.ProductDescription
}).ToList();
}
Also, there is no need to create a second SelectList
. Your GetAllLookupKey
method returns a collection of SelectListItem
and you can set that to your ViewData.
ViewData["ProductTypeId"] = _producttyperepository.GetAllLookupKey();
The SelectListItem
class is defined in the namespace Microsoft.AspNetCore.Mvc.Rendering;
So make sure you have a using statement which includes that namespace in your class.
using Microsoft.AspNetCore.Mvc.Rendering;
If this is in a different project than the one which has the Controllers. make sure your project has a reference to the assembly which has this namespace & class.
While that might fix our problem, SelectListItem
is a class to represent more of a UI layer concern. IMHO, You should not have your repository return that. Have your repository return more generic data (Ex : List of ProductType) and have your UI layer code (controller action/UI service layer etc) generate the list of SelectListItem objects from this ProductType list.