I want to create a form that will create a new item but that will pre-populate some data, espcially the date which I want to be DateTime.Now
and eventually link this data with the model, without leaving the option of my user to modify it.
我想创建一个表单来创建一个新项目,但是会预先填充一些数据,特别是我想成为DateTime.Now的日期,并最终将这些数据与模型相关联,而不会让我的用户选择修改它。
So far here's what I have done:
到目前为止,这是我所做的:
@using (Html.BeginForm()) {
{
var currentDate = DateTime.Now;
Model.m_OrderDate = currentDate;
}
@Html.ValidationSummary(true)
(...)
Order Date: @Html.DisplayFor(model => model.m_OrderDate)<br/>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
But the app crashes on runtime at the line Model.m_OrderDate = currenDate
saying that Object reference is not set to an instance of an object.
但是应用程序在运行时在Model.m_OrderDate = currenDate行崩溃,表示Object引用未设置为对象的实例。
I've looked through for many solutions but have yet to solve it. Can anyone help me? Thanks a lot!
我已经找了很多解决方案,但还没有解决它。谁能帮我?非常感谢!
1
In your model:
在你的模型中:
private DateTime? orderDate = null;
public DateTime OrderDate
{
get { return orderDate ?? DateTime.Now; }
set { orderDate = value; }
}
The only other piece is to make sure you pass an initialized model to your GET views, i.e.:
唯一的另一个方面是确保你将初始化的模型传递给你的GET视图,即:
public ActionResult MyAwesomeView()
{
return View(new MyModel());
}
The default will automatically populate.
默认将自动填充。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/03/04/481c0c27ef8241d124c4e380698bee70.html。