简体   繁体   中英

Repo method not returning data to controller (ASP.NET)

I have repo method to get data from db

Here is repo method

 public List<PatientMasterDataViewModel> GetPatientData(string name)
    {
        using (var ctx = new ApplicationDbContext())
        {
            List<PatientMasterDataViewModel> patientdata = new List<PatientMasterDataViewModel>();
            var items = ctx.Patients.Where(x => x.Name.Contains(name)).ToList();
            for (int i = 1; i < items.Count; i++)
            {
                patientdata.Add(new PatientMasterDataViewModel
                {
                    Id = items[i].Id,
                    Name = items[i].Name,
                    Birthday = items[i].Date_of_Birthday
                });
            }

            return patientdata;
        }
    }

after this I need to get this data in controller method

Here is controller method

public JsonResult PatientMasterDataInfo(string name)
    {
        var masterdatainfo = _repository.GetPatientData(name);
        return Json(masterdatainfo.ToArray(), JsonRequestBehavior.AllowGet);
    }

In Repo in items I have data

Here is screen

enter image description here

But for some reasons it not adding to patientdata and as result in controller I have null.

Where is my trouble?

You have loop started from 1. Please start it from 0 index.

public List<PatientMasterDataViewModel> GetPatientData(string name)
{
    using (var ctx = new ApplicationDbContext())
    {
        List<PatientMasterDataViewModel> patientdata = new List<PatientMasterDataViewModel>();
        var items = ctx.Patients.Where(x => x.Name.Contains(name)).ToList();
        for (int i = 0; i < items.Count; i++)
        {
            patientdata.Add(new PatientMasterDataViewModel
            {
                Id = items[i].Id,
                Name = items[i].Name,
                Birthday = items[i].Date_of_Birthday
            });
        }

        return patientdata;
    }
}

It should not be null as per your code what you have but i see one issue in your code which is your loop is string from 1 not 0 so change it to :

for (int i = 0; i < items.Count; i++)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM