I'm having a problem in my MVC project. When trying to create an object to add it to the db, it always returns null.
public class ListsModel
{
public EntitiesList EntityList { get; set; }
public List<string> AllGroups { get; set; }
}
public ActionResult Create()
{
ListsModel model = new ListsModel();
model.EntityList = new EntitiesList();
model.AllGroups = managerLists.GetAllListsKeys(); //For droplist
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ListsModel model)
{
if (ModelState.IsValid)
{
model.EntityList.List_CreatedTime = DateTime.Now;
managerLists.AddNewObject(model.EntityList);
return RedirectToAction("Index");
}
return View(model);
}
And a simple cshtml:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>EntitiesList</legend>
<div class="form-group">
@Html.LabelFor(model => model.EntityList.List_EntitityName)
@Html.DropDownListFor(model => model.AllGroups, new SelectList(Model.AllGroups),
new { @class = "form-control" })
<p class="help-block">@Html.ValidationMessageFor(model => model.EntityList.List_EntitityName)</p>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EntityList.List_EntityValue)
<input class="form-control" value="@Model.EntityList.List_EntityValue"/>
<p class="help-block">@Html.ValidationMessageFor(model => model.EntityList.List_EntityValue)</p>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EntityList.List_OrderByNumber)
<input class="form-control" value="@Model.EntityList.List_OrderByNumber"/>
<p class="help-block">@Html.ValidationMessageFor(model => model.EntityList.List_OrderByNumber)</p>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EntityList.List_Comments)
<textarea class="form-control" rows="3">@Model.EntityList.List_Comments</textarea>
<p class="help-block">@Html.ValidationMessageFor(model => model.EntityList.List_Comments)</p>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
When it's getting to the "model.EntityList.List_CreatedTime = DateTime.Now;" a null reference exception is thrown.
I tried to change the signature to "public ActionResult Create(ListsModel ListsModel)", as suggested here: Create view is posting null objects But I got the same results.
Hope you can help me.
modelcontain? Ismodelnull? Ismodel.EntityListnull? Debug is your friend! :) Place break-point onmodel.EntityList.List_CreatedTime = DateTime.Now;line and look at what everything is at that time.model.EntityList.List_CreatedTime = DateTime.Now;then are you still getting an error?