简体   繁体   中英

ASP.NET Core Razor Page create new for list always give System.NullReferenceException

when I open create new items open this page to enter the values for save to list but I always get null also inside the item there is group of item i show as drop list also give null error

in view

<input asp-for="@Model.Items.Id" />
<label asp-for="@Model.Items.Groups.Id">Group nme</label>
        <select asp-for="@Model.Items.Groups.Id"  asp-items="@(new SelectList(Model.AllGroup,"Id","GroupName" ))"></select>    

in CS file

    public class Items_Class
    {
        public int Id  { get; set; }
        public string ItemName { get; set; }
        public decimal ItemPrice { get; set; }
        public decimal ItemQuantity { get; set; }
        public Groups_Class Groups { get; set; }
    }


    public class CreateModel : PageModel
    {
       private readonly Groups_Methods g_Mrthod;

       [BindProperty]
       public Items_Class Items { get; set; }
       public List<Groups_Class> AllGroup { get; set; }
       
       public CreateModel(Groups_Methods  G_Mrthod)
       {
            g_Mrthod = G_Mrthod;
          
       }    
    

       public void OnGet()
       {
           AllGroup = g_Mrthod.GetAllGroups();        
       }
   } 

I've hard time to understand your problem. What are the steps?

  • Load the page
  • Add new item
  • Save
  • Server side has null values in ItemName, ItemPrice and ItemQuantity If these are the steps, please consider adding a

public void OnPost() and read https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-6.0&tabs=visual-studio#write-a-basic-form

You can try to set your Items and AllGroup :

[BindProperty]
        public Items_Class Items { get; set; } = new Items_Class();
        public List<Groups_Class> AllGroup { get; set; } = new List<Groups_Class>();

If it still doesn't work,try to check if g_Mrthod.GetAllGroups(); is null.

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