0

I'm new in the asp.net and try to create simle project, but have the iisue on the first steps: I have the NullReferenceException: Object reference not set to an instance of an object. in the view layer.

Packages in solution:

enter image description here

  • Startup.cs:

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllersWithViews();
          services.AddMvc();
          services.AddTransient<ICars, MockCars>();
          services.AddTransient<ICategories, MockCategories>();
          services.AddMvc(option => option.EnableEndpointRouting = false);
      }
    
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          app.UseDeveloperExceptionPage();
          app.UseStatusCodePages();
          app.UseStaticFiles();
          app.UseMvcWithDefaultRoute();
      }
    
  • Controller:

    public ViewResult List()
      {
          IEnumerable<Car> result = _cars.Cars; //not null - checked
          return View(result);
      }
    
  • View:

    @page
    @using Shop.Models
    @model IEnumerable<Car>
    
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    <div>
        <h2>All cars</h2>
        @{
            foreach (var car in Model)//    <----    NullReferenceException 
            {
                <div>
                    <h2>Model: @car.name. @car.shortDescriotion</h2>
                    <p>Price: @car.price.ToString("c")</p>
                </div>
            }
        }
    </div>
    </body>
    </html>
  • Exception:
    > NullReferenceException: Object reference not set to an instance of an
    > object. AspNetCore.Views_Cars_List.get_Model()
    > AspNetCore.Views_Cars_List.<ExecuteAsync>b__8_1() in List.cshtml
    > +
    >         foreach (var car in Model) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
    > AspNetCore.Views_Cars_List.ExecuteAsync() in List.cshtml
    > +
    >     Layout = null; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage
    > page, ViewContext context)
    > Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage
    > page, ViewContext context, bool invokeViewStarts)
    > Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext
    > context)
    > Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext
    > viewContext, string contentType, Nullable<int> statusCode)
    > Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext
    > viewContext, string contentType, Nullable<int> statusCode)
    > Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext
    > actionContext, IView view, ViewDataDictionary viewData,
    > ITempDataDictionary tempData, string contentType, Nullable<int>
    > statusCode)
    > Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext
    > context, ViewResult result)
    > Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext
    > context)
    > Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter,
    > TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next,
    > Scope scope, object state, bool isCompleted)
    > Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
    > context)

The video tutorial I followed all works well, but not in my case. Where could I was wrong?

1 Answer 1

1

When you use the @page directive, you tell that this view is a Razor Page View.

@page makes the file into an MVC action - which means that it handles requests directly, without going through a controller

Microsoft Docs: Introduction to Razor Pages in ASP.NET Core / Razor Pages

But you probably want to use ASP.NET Core MVC View:

In ASP.NET Core MVC the View is an HTML template with embedded Razor markup.

Microsoft Docs: Views in ASP.NET Core MVC


So, the fix should be simple. Remove the @page directive from your view and it should work.

@using Shop.Models
@model IEnumerable<Car>
    
@{
    Layout = null;
}
    
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div>
    <h2>All cars</h2>
    @{
        foreach (var car in Model)
        {
            <div>
                <h2>Model: @car.name. @car.shortDescriotion</h2>
                <p>Price: @car.price.ToString("c")</p>
            </div>
        }
    }
</div>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.