C# ASP.NET MVC Forms Creating a Basic Form Using Our Models

Andre Liverød
Andre Liverød
3,663 Points

Cannot run the code, getting errors in the Add() method

Got error when trying to run this code from the example:

    public ActionResult Add()
    {
        var entry = new Entry();
        {
            Date = DateTime.Today
        };
        return View(entry);
    }

Got two errors: ; expected The name "Date" does not exist in the current context.

I got it working by what i think should be the correct code, great if someone can verify that this is correct (at least the code runs and seems correct):

    public ActionResult Add()
    {
        var entry = new Entry();
        {
            var Date = DateTime.Today;
        };
        return View(entry);
    }
Andre Liverød
Andre Liverød
3,663 Points

Just an update, my code is not correct, it does not get the current date today and update the form with it. Probably because im making a new date variable but just using the Date variable gives me the error above.

1 Answer

Steven Parker
Steven Parker
203,729 Points

Your first code was almost correct, it just has a typo. There's a stray semicolon between the instantiation of entry and the brace on the following line that begins the object initializer. The reason you won't need a "var" in front of "Date" is because you're not creating a new variable but giving a value to the "Date" property of the newly created entry object.