我的MVC项目有问题。尝试创建对象以将其添加到db时,它始终返回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);
}
一个简单的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;”时抛出空引用异常。
我尝试将签名更改为“public ActionResult Create(ListsModel ListsModel)”,如下所示:Create view is posting null objects 但我得到了同样的结果。
希望你能帮助我。
答案 0 :(得分:2)
我认为问题在于您定义这样的输入的方式:
<input class="form-control" value="@Model.EntityList.List_EntityValue"/>
对于ASP MVC可以收集表单数据,输入应该具有与模型字段对应的Name属性。
尝试使用标准生成输入:
@Html.TextBoxFor(model => model.EntityList.List_EntityValue)
我建议你检查生成的html中的差异(看看asp mvc如何生成输入)。