I am showing checkbox list in my ASP.NET Core MVC project. I am pulling data from a database. I don't have any problems displaying one item, but if I want to show more than one item, I get a problem. How can I solve it?
public IActionResult Create()
{
var item = _context.Cihazlar.ToList();
StudentCourseViewModel m1 = new StudentCourseViewModel();
m1.AvailableCourses = item.Select(vm => new CheckBoxItem()
{
Id = vm.Id,
Title = vm.Model,
IsChecked = false
}).ToList();
return View(m1);
}
There is no problem in my code as above. The checkboxlist in m1
appears on the page, but if I make my code as below, I get an error.
public IActionResult Create()
{
var item = _context.Cihazlar.ToList();
StudentCourseViewModel m1 = new StudentCourseViewModel();
m1.AvailableCourses = item.Select(vm => new CheckBoxItem()
{
Id = vm.Id,
Title = vm.Model,
IsChecked = false
}).ToList();
var item2 = _context.HardwareSoftware.ToList();
StudentCourseViewModel m2 = new StudentCourseViewModel();
m2.AvailableCourses2 = item2.Select(vm => new CheckBoxItem()
{
Id = vm.Hardware_Software_Id,
Title = vm.Hardware_Software_Name,
IsChecked = false
}).ToList();
return View(m1, m2);
}
How can I show m1
and m2
at the same time?
CodePudding user response:
As suggested in the comment above, you can make like the following.
Declare a compound data model:
public class UnitedViewModel
{
public StudentCourseViewModel CihazlarCourses { get; set; } // Cihazlar
public StudentCourseViewModel HSCourses { get; set; } // HardwareSoftware
}
The Create
action method:
public IActionResult Create()
{
var model = new UnitedViewModel();
var item = _context.Cihazlar.ToList();
model.CihazlarCourses = new StudentCourseViewModel();
model.CihazlarCourses.AvailableCourses = item.Select(vm => new CheckBoxItem()
{
Id = vm.Id,
Title = vm.Model,
IsChecked = false
}).ToList();
var item2 = _context.HardwareSoftware.ToList();
model.HSCourses = new StudentCourseViewModel();
model.HSCourses.AvailableCourses = item2.Select(vm => new CheckBoxItem()
{
Id = vm.Hardware_Software_Id,
Title = vm.Hardware_Software_Name,
IsChecked = false
}).ToList();
return View(model);
}
Then declare the data view model in the Create.cshml
as below:
@model UnitedViewModel
.... Your code here will use the `@Model.CihazlarCourses` and the `@Model.HSCourses`