0

I am trying to get current time with DateTime.Now.ToString() and to assign as a value to Model.DatePosted, using Razor in my View.The problem is always when i try to add value to DatePosted I get NullReferenceException. I think I dont have problem with my code, but the error still remains. How can I fix that?

Here is the definition of DatePosted variable in my model table:

[Display(Name = "Date")]

    public string DatePosted { get; set; }

Here is the code in my View:

@model BicycleWorldShop.Models.Review

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string currentDate= DateTime.Now.ToString();
    Model.DatePosted = currentDate;

}

The error: enter image description here

Zoran Zoki
  • 128
  • 7
  • Read through the duplicate. The NRE is arguably the most frequently occurring exception in .net so knowing how to troubleshoot it is vital for any .net developer. – Igor Oct 09 '18 at 21:41
  • Once you do that hover over the highlight line and figure out *what is null*. Then go back to your Action code (method that calls the razor view) and figure out why could that be null – Igor Oct 09 '18 at 21:41
  • You set the value in the GET method before you pass the model to the view - but it looks like you did not even pass a model to the view - `Review model = new Review{ DatePosted = DateTime.Now }; return View(model);` (and its a `DateTime` so why have you made the property a `string`?) –  Oct 09 '18 at 22:33
  • Thanks @Igor, I was trying to set values to get method and that was my unintentionally mistake. The view just show values from the model, but the actual assigning or saving is done into the controller! Cheers ! – Zoran Zoki Oct 09 '18 at 22:54

0 Answers0