我在我的MVC項目中遇到問題。當試圖創建一個對象將其添加到數據庫時,它總是返回null。MVC創建返回空對象
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);
}
和一個簡單的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>
}
當它越來越向 「model.EntityList.List_CreatedTime = DateTime.Now;」引發空引用異常。
我試圖更改簽名爲「公衆的ActionResult創建(ListsModel ListsModel)」,因爲這裏建議:Create view is posting null objects 但我得到了相同的結果。
希望你能幫助我。
如果你調試這個'model'包含什麼?模型是否爲空? 'model.EntityList'爲空嗎?調試是你的朋友! :)將斷點放在'model.EntityList.List_CreatedTime = DateTime.Now;'行並查看當時的所有內容。 – Belogix
您是否在cshtml中指定了模型? – Marcus
可能是不相關的,但你應該使用EditorFor,TextAreaFor等 – markpsmith