locked
Get count of total records in razor pages and using the List Function RRS feed

  • Question

  • User-973886032 posted

    Hi guys

    I started playing around with razor pages, and wonder how to get the total count of a record and also how to use List generic functions. 

    In my old MVC applications I simply added List to the model directive e.g.  Kindly note, I have edited the code and removed the lengthy unnecessary bits.

    My aim is to make dynamic content and display them in a div row of 3 horizontally and then as many vertically

    Hence I added the list function to the model directive

    @model IList<Xadosh.Models.Department.Departments>

    Here is my code, basic code

    --- ~Code Behind
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.EntityFrameworkCore;
    using VirtualMarkets.Models.Department;
    using VirtualMarkets.Web.Classes;
    
    namespace VirtualMarkets.Web.Pages.test
    {
        public class IndexModel : PageModel
        {
            private readonly VirtualMarkets.Web.Classes.MyDbContext _context;
    
            public IndexModel(VirtualMarkets.Web.Classes.MyDbContext context)
            {
                _context = context;
            }
    
            public IList<Tbl_Departments> Tbl_Departments { get;set; }
    
            public async Task OnGetAsync()
            {
                Tbl_Departments = await _context.Tbl_Departments.ToListAsync();
            }
        }
    }
    
    
    
    
    
    Razor page
    
    @page
    @model IList<VirtualMarkets.Web.Pages.Cart.IndexModel>
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
               <div class="text-center"><h5>General Department - (@(Model.Count()))</h5></div>
    
    
    @for (var i = 0; i < Model.Count(); i++)
    {
    
    
     <div class="col-md-4 text-center   classify">
    
                                <a href="@Model[i].Description_Short">
                                    @Model[i].Department_Name<br />
                                    <div>
                                        <img src="~/images/Department_Categories/@(Model[i].DepartmentID).png" alt="@(Model[i].Department_Name)" class="img-fluid" />
                                        <br />
    
                                      
                                        @Model[i].Description_Long
                                        <br /><div class="small">@Model[i].Description_Short</div>
                                    </div>
                                </a><br /><hr />
    
                            </div>
    
    
    
        }

     and my model

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace VirtualMarkets.Models.Department
    {
        public class Tbl_Departments
        {
          
                [Key]
                public int DepartmentID { get; set; }
            
                [Required]
                [StringLength(150, ErrorMessage = "First name cannot be longer than 150 characters.")]
                public string Department_Name { get; set; }
              
                [Required]
                public string Description_Long { get; set; }
             
                [Required]
                [StringLength(150, ErrorMessage = "First name cannot be longer than 150 characters.")]
                public string Description_Short { get; set; }
                public bool IsEnabled { get; set; }
    
    
    
    
              
          
        }
    }
    

    I get this error

    An unhandled exception occurred while processing the request.
    
    InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.IList`1[VirtualMarkets.Web.Pages.Cart.IndexModel]' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable<int>[] parameterMap)
    Stack 
     Query 
     Cookies 
     Headers 
     Routing 
     
    
    InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.IList`1[VirtualMarkets.Web.Pages.Cart.IndexModel]' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable<int>[] parameterMap)
    
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(Type instanceType, Type[] argumentTypes)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelActivatorProvider.CreateActivator(CompiledPageActionDescriptor actionDescriptor)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.CreateModelFactory(CompiledPageActionDescriptor descriptor)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvokerProvider.CreateCacheEntry(ActionInvokerProviderContext context, FilterItem[] cachedFilters)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
    
    
    Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
    
    
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory+<>c__DisplayClass7_0.<CreateRequestDelegate>b__0(HttpContext context)
    
    
    Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    
    
    
    
    
    Show raw exception details 
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
      
      
      
      
      
      
      
    
    
    
    
    
    
    
    
    
    
      
      
      
    
    
    
    
    
    
    
    
    
      
     

    Friday, August 21, 2020 3:48 PM

Answers

  • User-17257777 posted

    Hi afrika,

    Razor page is different form MVC, the model in page is IndexModel. I think you want to get the count of Tbl_Departments in IndexModel, you should use @Model.Model.Tbl_Departments, change like below:

    @page
    @model VirtualMarkets.Web.Pages.Cart.IndexModel
    @{
        ViewData["Title"] = "Index";
    }
    
    <div class="text-center"><h5>General Department - (@(Model.Tbl_Departments.Count()))</h5></div>
    
    
    @for (var i = 0; i < Model.Tbl_Departments.Count(); i++)
    {
    
    
        <div class="col-md-4 text-center   classify">
    
            <a href="@Model.Tbl_Departments[i].Description_Short">
                @Model.Tbl_Departments[i].Department_Name<br />
                <div>
                    <img src="~/images/Department_Categories/@(Model.Tbl_Departments[i].DepartmentID).png" alt="@(Model.Tbl_Departments[i].Department_Name)" class="img-fluid" />
                    <br />
    
    
                    @Model.Tbl_Departments[i].Description_Long
                    <br /><div class="small">@Model.Tbl_Departments[i].Description_Short</div>
                </div>
            </a><br /><hr />
    
        </div>
    
    
    
    }

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 25, 2020 9:10 AM

All replies

  • User756251838 posted

    Hello,

    Each Razor Page can only have one Model and that model should be a PageModel, and you can have various type of models in your PageModel and use them in the Razor Page Template (cshtml)

    Friday, August 21, 2020 7:49 PM
  • User-973886032 posted

    thanks, but does anyone know how to get the count of the records for both the model and navigation property ?

    Saturday, August 22, 2020 9:29 AM
  • User-17257777 posted

    Hi afrika,

    Razor page is different form MVC, the model in page is IndexModel. I think you want to get the count of Tbl_Departments in IndexModel, you should use @Model.Model.Tbl_Departments, change like below:

    @page
    @model VirtualMarkets.Web.Pages.Cart.IndexModel
    @{
        ViewData["Title"] = "Index";
    }
    
    <div class="text-center"><h5>General Department - (@(Model.Tbl_Departments.Count()))</h5></div>
    
    
    @for (var i = 0; i < Model.Tbl_Departments.Count(); i++)
    {
    
    
        <div class="col-md-4 text-center   classify">
    
            <a href="@Model.Tbl_Departments[i].Description_Short">
                @Model.Tbl_Departments[i].Department_Name<br />
                <div>
                    <img src="~/images/Department_Categories/@(Model.Tbl_Departments[i].DepartmentID).png" alt="@(Model.Tbl_Departments[i].Department_Name)" class="img-fluid" />
                    <br />
    
    
                    @Model.Tbl_Departments[i].Description_Long
                    <br /><div class="small">@Model.Tbl_Departments[i].Description_Short</div>
                </div>
            </a><br /><hr />
    
        </div>
    
    
    
    }

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 25, 2020 9:10 AM
  • User-973886032 posted

    Yes that works

    There is a very subtle change from the MVC model. 

    thanks a lot

    Tuesday, August 25, 2020 12:04 PM