简体   繁体   中英

ASP.NET MVC Object reference error

I have a very simple starter .NET application with this method in my controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SampleMVC.Models;

namespace SampleMVC
{
    public class TurtleController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Detail( int id ) {
            var turtle = new TurtleModel{ id = 1, title = "Pink Turtle" };
            return View("Detail",turtle);
        }
    }

My TurtleModel looks like this:

using System;

namespace SampleMVC.Models
{
    public class TurtleModel
    {
        public int id { get; set; }
        public string title { get; set; }
    }
}

and my view looks like this:

@page
@model SampleMVC.Models.TurtleModel;
@{
    <p>tester @Model.title</p>
}

Startup.cs (Routes)

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
}

However I'm getting a Null pointer / Object reference error when trying to view the URL /Turtle/Detail/1 . Wondering if you can point me in the right direction? I have debugged the Controller and the turtleModel is definitely instantiated, so I don't see why the view thinks it is not after it has been passed down to it.

The problem appeared to be in the view:

@page
@model SampleMVC.Models.TurtleModel;
@{
    <p>tester @Model.title</p>
}

Changed to

@model SampleMVC.Models.TurtleModel;
@{
    <p>tester @Model.title</p>
}

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