Ok, so this problem seems incredibly weird to me. I have a view that is used for both editing and creating new articles. Editing existing articles works perfectly, however creating new ones gives me a null reference exception ("Object reference not set to an instance of an object").
Here's my code:
//Return Edit/New partial view. New if Id < 0 (will be -1)
public ActionResult Edit(int Id)
{
Models.Article a;
if (Id > 0)
{
Models.Entities db = new Models.Entities();
a = db.Article.FirstOrDefault(dba => dba.Id == Id);
}
else
{
a = new Models.Article();
a.Id = -1;
a.DateProperty = DateTime.Now; //Repeat for each date property
a.Property = ""; //Repeat for every string property
}
return PartialView("~/Views/Article/Edit.cshtml", a);
}
I then return a view that contains the following (and more along the same lines):
<label for="txtTitle">Title</label>
<input type="text" id="txtTitle" data-originalvalue="@Model.Title" value="@Model.Title" />
<span class="actionButton actionUndo revert" title="Undo Changes">Revert</span>
<label for="txtPublishDate">Publish Date</label>
<input type="text" id="txtPublishDate" class="datePicker" data-originalvalue="@Model.PublishDate.ToShortDateString()" value="@Model.PublishDate.ToShortDateString()" />
<span class="actionButton actionUndo revert" title="Undo Changes">Revert</span>
For some reason every time this Article/Edit?Id=-1
is called the page loads up and I get the afore mentioned error. The code that's highlighted is in the data-originalvalue
attribute (a custom HTML5 data field).
If I REMOVE those custom data fields, I get the same error, but [No relevant source lines]
.
I am very confused as to why this happens.
The models themselves are generated from the database using ADO.Net and the project uses MVC 4 and .Net 4.5.