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>

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

But still the textbox and label appear during the create view... It errors if i remove it from the codes
@Jed. Remove all this: <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> and it will be fine, (if this is what you want. )
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. Look for the inner exception.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.