Daza Aza
Daza Aza

Reputation: 498

Automatically set DateTime in new record

Automatically updating the dateTime in edit view when saved - this works fine. I have used the following code to acheive this...

@Html.HiddenFor(model => model.Posted, Model.Posted = DateTime.Now)

the poblem lies with the create new record. I am trying to implement automatic datetime entry however the code above does not work?

The error which is being displayed is:

NullReferenceException was unhandled by user code (object reference not set to an instance of an object

the following code is from the controller:

    //
    // GET: /cars/Create

    public ActionResult Create()
    {
        return View();
    }

    // POST: /cars/Create



    [HttpPost]
    [ValidateInput(false)]

    public ActionResult Create(cars newsitem)
    {
        try
        {
            using (var db = new carsNewsEntities())
            {
                db.cars.Add(cars);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

Upvotes: 2

Views: 1686

Answers (3)

Chetan Pangam
Chetan Pangam

Reputation: 370

Even though above solution worked but If you have different columns as CreatedDate and ModifiedDate then above solution is not working. It is setting createdDate null after updating record. to overcome that I tried below line in Edit View and It worked.

@Html.HiddenFor(model => model.EntryDateTimeStamp, Model.EntryDateTimeStamp = Model.EntryDateTimeStamp)
@Html.HiddenFor(model => model.ModifiedDateTime, Model.ModifiedDateTime = DateTime.Now)

and similarly in Create View I did similar thing

@Html.HiddenFor(model => model.EntryDateTimeStamp, Model.EntryDateTimeStamp = DateTime.Now)

and pass new object in controller like above mentioned answer.

 return View(new NewsItem ()); 

Upvotes: 0

Jim D'Angelo
Jim D'Angelo

Reputation: 3952

Try passing a new object to your view:

// 
// GET: /News/Create 

public ActionResult Create() 
{ 
    return View(new NewsItem ()); 
}

Though I would set that field in the controller:

// 
// GET: /News/Create 

public ActionResult Create() 
{
    var viewModel = new NewsItem { Posted = DateTime.Now };
    return View(viewModel); 
} 

Upvotes: 0

Rikon
Rikon

Reputation: 2706

Instead of putting the responsibility of knowing how to initialize a new object on the view, I would suggest setting that date time in either 1) a static factory create method that your services would know to call or 2) the empty constructor of your model object.

public MyModelObject()
{
    Posted = DateTime.Now;
}

Btw, I think you're getting the null reference exception because your "Posted" property is likely not nullable... If my guess is right, you may be able to still get your way to work by making it nullable (but you loose the non-null enforcement)...

Upvotes: 1

Related Questions