locked
Add objects to foregin table using Tag Helpers RRS feed

  • Question

  • User-865174439 posted

    I try add in one View element to two table Adventure and AdventureCategory. Tables are connected relation many-to-one

    AdventureModel

    public class Adventure
    {
    
      [Key]
      public int idAdventure {get; set;}
      public string adventureName {get; set;}
    
      public virtual ICollection<AdventureCategory> AdventureCategory{ get; set; }
    }
    

    AdventureCategoryModel

    public class AdventureCategory
    {
    
      [Key]
      public int idAdventureCategory {get; set;}
    
      [ForeignKey("Adventure")]
      public int idAdventure {get; set; }
    
      public string categoryName {get; set;}
    
      public virtual Adventure Adventure {get; set; }
    }
    

    In View i have many checkbox where i can choose few AdventureCategory

    <input type="text" asp-for="adventureName"/> //field from Adventure table, it's ok
    
     <input type="checkbox" for="AdventureCategory.categoryName" value="swimming"> 
    //this return error "Element <ICollection>AdventureCategory does not contain a definition for adventureName"
    
     <input type="checkbox" for="AdventureCategory.categoryName" value="running"> 
    //this return error "Element <ICollection>AdventureCategory does not contain a definition for adventureName"
    
     <input type="checkbox" for="AdventureCategory.categoryName" value="walking"> 
    //this return error "Element <ICollection>AdventureCategory does not contain a definition for adventureName"
    
    Tuesday, June 9, 2020 6:48 PM

All replies

  • User-719153870 posted

    Hi polunyt,

    If I understand correctly, you want to create an Adventure object with swimming or/and running or/and walking as its AdventureCategory value.

    If this is the case, I don't think asp-for will automatically do the whole process for you.

    Please refer to How to correctly submit checkbox values to controller in ASP.NET MVC, use CheckBoxFor instead and add bool IsSelected property.

    Best Regard,

    Yang Shen

    Wednesday, June 10, 2020 6:44 AM