locked
ASP.NET Core RRS feed

  • Question

  • User-1539946879 posted

    I want to get the total number of students classwise and according to gender. I have tries this:

    ViewModel

    public class StudentNumberViewModel
    {
    public StudentNumberViewModel()
    {
    modelList = new List<StudentNumberViewModel>();
    }
    public string Class { get; set; }
    public int Male { get; set; }
    public int Female { get; set; }
    public int Others { get; set; }

    public List<StudentNumberViewModel> modelList { get; set; }
    }

    Controller

    public IActionResult StudentList(StudentNumberViewModel model)
    {
    var lstModel = new List<StudentNumberViewModel>();
    var classData = _classRepository.GetAll(1).ToList();
    foreach (var cls in classData)
    {
    model.Female = _studentRepository.GetAllByClass(1, cls.Id).Where(x => x.Gender == "Female").Count();
    model.Male = _studentRepository.GetAllByClass(1, cls.Id).Where(x => x.Gender == "Male").Count();
    model.Others = _studentRepository.GetAllByClass(1, cls.Id).Where(x => x.Gender == "Others").Count();
    //var classData1 = _classRepository.Get(cls.Id);
    //model.Class = classData1.ClassName;
    lstModel.Add(model);
    }
    return View(lstModel);
    }

    I only get the total number of student of class 10 but I need from 1 to 10.

    Please help me.

    Thank You.

    Thursday, December 27, 2018 10:15 AM

All replies

  • User465171450 posted

    You have a list of StudentNumberViewModels that you are passing into a new view. Look at your foreach. All you are doing is effectively updating the single model that was passed into the app. Your list is now made up with references to that single object most likely. Instead, create a new StudentNumberViewModel for each iteration in your foreach and add it to the list.

    Also, note that your foreach could blow up. If, for example there aren't any males in a class the list will be null and could fail.

    Thursday, December 27, 2018 3:28 PM