Home > Software engineering >  How to add data from controller into nested model in ASP.NET Core?
How to add data from controller into nested model in ASP.NET Core?

Time:10-03

I want to add data in relational model

public class person
{
    public int id { get; set; }
    public string name { get; set; }
    public virtual ICollection<phone> Phones { get; set; }
}

public class Phone
{
    public int id { get; set; }
    public string Phonenumber { get; set; }
    public int personid { get; set; }
    public virtual person Person { get; set; }
    public virtual ICollection<phone> Phones { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}                   

public class Address
{
    public int id { get; set; }
    public string desc { get; set; }
}

When I add data to addresses

for (int i = 0; i < model.count; i  )
{
    person.phones[0].Addresses[i]= model;
}

I get this message:

Must be non-negative and less than the size of the collection

CodePudding user response:

hope that I'm not being stupid here but you might want to check the capitalisation of the properties.

Notably the person has a parameter 'Phones' but it seems like you are trying to access 'phones'. Not sure if it will make a difference but I guess it might be worth a try.

CodePudding user response:

in controller

public IActionresult createperson(PersonModel model, string[] Addmodel){
    if(model.phones != null)
    {
        int i= 0;
        foreach(item in addmodel)
        {               
            var newmodel= new Addressmodel();
            mewmodel.desc= item;
            model.Phones[0].Address[i]= newmodel;
            i  ;
        }
    }
}

I add breakpoint in model.Phones[0].Address[i]= newmodel; and i saw can't access Address[i] and i get this error

Must be non-negative and less than the size of the collection

  • Related