Vinz with the Z
Vinz with the Z

Reputation: 157

Saving null DateTime on mvc3

I'm having a problem in saving DateTime in sql. My problem is that I want to save DateTime that has null value. Can anyone help me with this issue?

Here's my code:

Html:

<div class="infoHeader">
            Worker Skill</div>

             <div class="main">
            @using (Html.BeginForm("SkillsTestSave", "Worker", FormMethod.Post, new { id = "skillForm" }))
            {
                <input type="hidden" id="skillId" name="skillId" value="@workerId" />

                <p>
                    <label for="skillName">
                        <abbr title="This is a required field.">
                            <em><font color="red">*</font></em></abbr>
                        Skill Name</label>
                    <span>
                        <input type="text" id="txtSkillName" name="txtSkillName" class="validate[required,maxSize[50]] inputLong" value="@workerSkillName" />
                    </span>
                </p>
                <p>
                    <label for="skillLevel">
                        <abbr title="This is a required field.">
                            <em><font color="red">*</font></em></abbr>
                        Skill Level</label>
                 <span>
                        <input type="hidden" id="txtSkillLevel" name="txtSkillLevel" class="validate[required] inputLong"
                            value="@workerSkillLevel" />
                        <input type="radio" id="radiolvl1" name="radiolvl" class="radiolvl" value="1" />
                        <input type="radio" id="radiolvl2" name="radiolvl" class="radiolvl" value="2" />
                        <input type="radio" id="radiolvl3" name="radiolvl" class="radiolvl" value="3" />
                        <input type="radio" id="radiolvl4" name="radiolvl" class="radiolvl" value="4" />
                        <input type="radio" id="radiolvl5" name="radiolvl" class="radiolvl" value="5" />
                    </span>

                    @*<span>
                        <input type="text" id="txtSkillLevel" name="txtSkillLevel" class="validate[required,maxSize[100]] inputLong" value="@workerSkillLevel" />
                    </span>*@
                </p>
                <p>
                    <label for="skilldescription">
                        Skill Description</label>
                    <span>
                        <textarea style="overflow: auto; resize: none" rows="3" cols="27" id="txtSkillDescription"
                            name="txtSkillDescription">@workerSkillDescription</textarea>
                    </span>
                </p>   
                <p>
                    <label for="skillCertificate">
                      @*  <abbr title="This is a required field.">
                            <em><font color="red">*</font></em></abbr>*@
                        Certificate</label>
                    <span>
                        <input type="text" id="txtSkillCertificate" name="txtSkillCertificate" @*class="validate[required,maxSize[200]] inputLong"*@ value="@workerCertificate" />
                    </span>
                </p>
                <p>
                    <label for="skillDateAcquired">
                       @* <abbr title="This is a required field.">
                            <em><font color="red">*</font></em></abbr>*@
                        Date Acquired</label>
                    <span>
                        <input id="skillDateAcquired"  name ="skillDateAcquired"  value = "@workerDateAcquired"  style="padding: 0 0 0 0 !important"/>
                    </span>
                </p>
                <script type="text/javascript">
                    $(document).ready(function () {

                        $("#skillDateAcquired").kendoDatePicker({
                            max: new Date(2050, 0, 12)
                        });

                        $("#skillDateAcquired").attr("readonly", "readonly");
                        //                        $("#skillDateAcquired").attr("class", "validate[required]");
                        $("#skillDateAcquired").attr("aria-disabled", "true");



                    });

                </script>
                <p>
                    <span>
                        <input type="submit" id="skillBtn" class="styledButton" value="Add" />
                    </span>
                </p>
            }
        </div>

My controller on saving:

[Authorize]
        [HttpPost]
        public ActionResult SkillsTestSave(FormCollection formCollection)
        {
            String msg = String.Empty;
            String workerId = formCollection["SkillId"];
            String workerSkillId = formCollection["workerSkillId"];
            String workerSkillName = formCollection["txtSkillName"];
            String workerSkillLevel = formCollection["txtSkillLevel"];
            String workerSkillDescription = formCollection["txtSkillDescription"];
            String workerCertificate = formCollection["txtSkillCertificate"];
            String workerDateAcquired = formCollection["skillDateAcquired"];
            Worker_Skills skill = new Worker_Skills();
            try
            {
                if (String.IsNullOrWhiteSpace(workerSkillId) || workerSkillId == "0")
                {
                    skill.Worker_ID = Convert.ToInt32(workerId);
                    skill.SkillName = workerSkillName.Trim();
                    skill.SkillLevel = workerSkillLevel.Trim();
                    skill.SkillDescription = workerSkillDescription.Trim();
                    skill.Certificate = workerCertificate.Trim();
                    skill.DateAcquired = Convert.ToDateTime(workerDateAcquired);
                    skill.DateCreated = DateTime.UtcNow;
                    skill.DateModified = DateTime.UtcNow;
                    skill.CreatedBy = User.Identity.Name;
                    skill.ModifiedBy = User.Identity.Name;

                    db.Worker_Skills.Add(skill);
                }
             }
             catch (Exception)
             {
                 msg = "Failed to save";
             }
             db.SaveChanges();
             if (String.IsNullOrWhiteSpace((msg)))
             { TempData["message"] = "Saved Successfully."; }
             else if (msg != "")
             { TempData["message"] = msg; }


             if (Roles.IsUserInRole("Worker"))
             {
                 var url = UrlHelper.GenerateUrl(
                      null,
                      "WorkerIndex",
                      "Worker",
                      null,
                      null,
                      "anchorSkills",
                      new RouteValueDictionary(new { workerId = workerId }),
                      Url.RouteCollection,
                      Url.RequestContext,
                      false
                  );
                 return Redirect(url);
             }
             else
             {

                 var url = UrlHelper.GenerateUrl(
                         null,
                         "workerDetails",
                         "Worker",
                         null,
                         null,
                         "anchorSkills",
                         new RouteValueDictionary(new { workerId = workerId }),
                         Url.RouteCollection,
                         Url.RequestContext,
                         false
                     );
                 return Redirect(url);
             }

        }

I set the value of dateacquired into nullable DateTime in my table:

namespace SmartTimers.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Worker_Skills
    {
        public int ID { get; set; }
        public int Worker_ID { get; set; }
        public string SkillName { get; set; }
        public bool LogicalDelete { get; set; }
        public string SkillLevel { get; set; }
        public string SkillDescription { get; set; }
        public string Certificate { get; set; }
        public Nullable<System.DateTime> DateAcquired { get; set; }
        public System.DateTime DateCreated { get; set; }
        public string CreatedBy { get; set; }
        public System.DateTime DateModified { get; set; }
        public string ModifiedBy { get; set; }

        public virtual Worker Worker { get; set; }
    }
}

Another thought: If I can't set it to null, how can I set it to DateTime that is to now?

Upvotes: 2

Views: 768

Answers (1)

KJ3
KJ3

Reputation: 5298

Not sure I fully understand the question, you're saying if the entered value is null, you want to save it as DateTime.Now and if not you want to save it as what was entered? In that case,

DateTime enteredDate;
DateTime.TryParse(workerDateAcquired, out enteredDate);

skill.DateAcquired = enteredDate.Equals(DateTime.MinValue) ? DateTime.Now : enteredDate;

This tries to parse the entered date as a valid dateTime, if it can't, enteredDate will be the minimum dateTime value. The last line sets DateAcquired to DateTime.Now if the enteredDate couldn't be parsed (you could set that to whatever you want) and enteredDate if it was able to parse a date out of it.

Upvotes: 2

Related Questions