我正在MVC项目中构建第三个或多或少相同的表单(这意味着我正在复制和粘贴以节省时间)。这种只有一个控件的新形式在@ Html.AntiForgeryToken()行上引发了空引用错误。
@model SubSheets.ViewModels.TaskItemViewModel
@using (Html.BeginForm("CreateTaskItem", "TaskItems"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(m => m.Name, "Task Name", new {@class = "control-label col-md-2"})
<div class="col-md-2">
@Html.EditorFor(m => m.Name, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(m => m.Name, "", new {@class = "text-danger"})
</div>
</div>
</div>
}
[Authorize]
[HttpPost]
public ActionResult CreateTaskItem(TaskItemViewModel viewModel)
{
/* db context actions */
return View("../WorkItems/CreateWorkItem");
}
表单过得很好,数据也保存得很好。但是,我得到了空引用错误,第13行:
对象引用未设置为对象的实例。
Line 11: @using (Html.BeginForm())
Line 12: {
Line 13: @Html.AntiForgeryToken()
Line 14:
Line 15: <div class="form-horizontal">
我以为我理解HTML帮手添加了一个隐藏的表单字段,以确保发帖请求不是来自第三方域。我没想到会从表单字段中获取空引用异常吗?