0

This is a code snippet of my my Create.cshtml in my ASP.NET MVC3.. I don't know how to save the DateAdded as DateTimeNow. Im using CRUDE to Create a new Record. I already tried to remove the code below and replace it with DateTimeNow (system time) without displaying the textbox and label from the code below:

<div class="editor-label">
    @Html.LabelFor(model => model.DateAdded)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DateAdded)
    @Html.ValidationMessageFor(model => model.DateAdded)
</div>

Here's my snippet of Create.cshtml

@model PhoneBook.Models.Contact

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
<fieldset>
    <legend>Contact</legend>
    <div class="editor-label">
        @Html.LabelFor(model => model.DateAdded)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DateAdded)
        @Html.ValidationMessageFor(model => model.DateAdded)
    </div>

  <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
gdoron
  • 147,333
  • 58
  • 291
  • 367
Jed
  • 1,664
  • 8
  • 33
  • 65

1 Answers1

3

You should give the DateTime.Now value in the controller:

[HttpPost]
public ActionResult Foo(Contact model)
{
    model.DateAdded = DateTime.Now;
    ...
    ...
}

Or if you want the datetime to be in the page when it is rendered:

[HttpGet]
public ActionResult Foo()
{
    Contact model = new Contact{ DateAdded = DateTime.Now};

    return View(model);
}
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • But still the textbox and label appear during the create view... It errors if i remove it from the codes – Jed May 18 '12 at 09:46
  • 1
    @Jed. Remove all this: `Contact
    @Html.LabelFor(model => model.DateAdded)
    @Html.EditorFor(model => model.DateAdded) @Html.ValidationMessageFor(model => model.DateAdded)
    ` and it will be fine, (if this is what you want. )
    – gdoron May 18 '12 at 09:48
  • I have problem, if i delete the codes your suggested to be erased.. The db.SaveChanges(); inside the code Create Method gives an error. It says "An error occured while updatin the entries." – Jed May 18 '12 at 10:03
  • @Jed. Look for the inner exception. – gdoron May 18 '12 at 10:04
  • 1
    Thank you very much gordon. I figured it out already. I placed the code you suggested in the wrong method. I must put it in the `Create` method – Jed May 18 '12 at 10:16