frc frc - 25 days ago 7
C# Question

Passing a list of rows from another table in a model

I have a

Products
table and a
ProductVM
view model, and in
ProductVM
I want need to have a list of rows from another table (
Categories
), so I can display that in a dropdown list when adding a new product.

I have not been able to that so I've used
ViewBag
to pass to the view and make a dropdown list, but I know I should do it via the model but don't know how.

ProductVM

public class ProductVM
{

public ProductVM()
{
}

public ProductVM(ProductDTO productDTO)
{
Id = productDTO.Id;
Name = productDTO.Name;
Description = productDTO.Description;
CategoryId = productDTO.Id;
}

public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int? CategoryId { get; set; }
}


ActionMethod:

public ActionResult AddProduct()
{
Db db = new Db();

var result = from r in db.Categories
select new { r.Name, r.Id };

ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");

return View();
}


The
Categories
table just has 2 columns,
Id
and
Name
.

And to be clear, what I have now works, I just wanna do it via the model completely and not use
ViewBag
.

Answer

Add a property to your view model

public IEnumerable<SelectListItem> Categories { get; set; }

and in the controller use

var model = new ProductVM()
{
    Categories = new SelectList(db.Categories, "Id", "Name"
}; 
return View(model);

Note you can also use

Categories = db.Categories.Select(x => new SelectListItem()
{
    Value = x.Id.ToString(), // assumes Id is not typeof string
    Text = x.Name
})
Comments