locked
NullReferenceException: Object reference not set to an instance of an object. RRS feed

  • Question

  • User577052021 posted

    Hi everybody! I have got the following exception while running code in ASP.NET MVC and requested to help me

    "NullReferenceException: Object reference not set to an instance of an object.

    AspNetCore.Views_Home_Index.ExecuteAsync() in Index.cshtml, line 10

    NullReferenceException: Object reference not set to an instance of an object.

    • AspNetCore.Views_Home_Index.ExecuteAsync() in Index.cshtml


      1. <h2>@Model.PlayerName.Count()</h2> "

    Code details is given below

    HomeController.cs

    namespace Leave_Management.Controllers
    {
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;

            public HomeController(ILogger<HomeController> logger)
            {
                _logger = logger;
            }

            public IActionResult Index()
            {

                Models.Raptors player = new Models.Raptors();
                
                    player.PlayerName = "XYZ";
                player.ArivalDate = new DateTime(2020, 2, 20);
               
                return View();
               
            }

            public IActionResult Privacy()
            {
                return View();
            }

            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
            public IActionResult Error()
            {
                return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
            }
        }
    }

    index.cshtml

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
        <h1> This is my <b> first assignment</b></h1>
        <h2>@Model.PlayerName.Count()</h2>
        <span>has signed agreement on @Model.ArivalDate.ToString()</span>

    </div>

    model.cs code

    namespace Leave_Management.Models
    {
        public class Raptors
        {
            public string PlayerName { get; set; }
            public DateTime ArivalDate { get; set; }
        }
    }

    Thursday, February 25, 2021 1:23 PM

Answers

  • User1312693872 posted

    Hi,Tariqbaabaa

    You should pass the player to the view, or the view can't get the model value:

    public IActionResult Index()
                {
                    Raptors player = new Raptors();
                    player.PlayerName = "XYZ";
                    player.ArivalDate = new DateTime(2020, 2, 20);
                    return View(player);
                }

    You can learn tutorials in mgebhard's links.

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2021 2:10 AM

All replies