簡體   English   中英

ASP.NET MVC對象參考錯誤

[英]ASP.NET MVC Object reference error

我的控制器中有一個使用此方法的非常簡單的.NET入門應用程序:

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);
        }
    }

我的TurtleModel看起來像這樣:

using System;

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

我的看法如下所示:

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

Startup.cs(路由)

 // 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?}");
            });
}

但是,當嘗試查看URL /Turtle/Detail/1時,出現Null指針/對象引用錯誤。 想知道您能否指出正確的方向嗎? 我已經調試了Controller,並且無疑將turtleModel實例化,所以我不明白為什么視圖認為它傳遞給它后就認為它不是。

問題似乎在於:

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

變成

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM