我的TextBoxFor
视图中有以下CreateOrEdit
:
@Html.TextBoxFor(model => model.Date.Value.ToShortDateString(),
new {@readonly = true, @class = "form-control"})
当然我不能这样使用它,因为我收到以下错误:
模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。
所以我改变了我的代码:
@{
var m = Model.Date.Value.ToShortDateString();
@Html.TextBoxFor(model => m, new {@readonly = true, @class = "form-control"})
@Html.ValidationMessageFor(model => model.Date)
}
现在它不再给我上面的错误并且它适用于编辑操作,因为我已经有一个Model实例,因此以下行在Edit操作方法中是正确的,但在Create action方法中没有:
var m = Model.Date.Value.ToShortDateString();
我的问题是当我使用Create动作方法时因为我没有Model实例,所以我得到了异常。我该如何解决这个问题?
答案 0 :(得分:1)
NullReferenceException
视图中的Create.cshtml
将是未将模型传递给视图的结果,您应该始终这样做。对于Create()
方法,只需初始化并将模型的新实例传递给GET方法中的视图。
public ActionResult Create()
{
var model = new yourModel();
return View(model);
}