简体   繁体   中英

Mvc pre-populate a date field with data that will link to the model

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.

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.

I've looked through for many solutions but have yet to solve it. Can anyone help me? Thanks a lot!

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, ie:

public ActionResult MyAwesomeView()
{
    return View(new MyModel());
}

The default will automatically populate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM