在mvc3上保存null DateTime

时间:2014-03-24 01:57:03

标签: c# sql asp.net-mvc-3 entity-framework datetime

我在sql中保存DateTime时遇到问题。我的问题是我想保存具有空值的DateTime。任何人都可以帮我解决这个问题吗?

这是我的代码:

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>

我的保存控制器:

[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);
             }

        }

我在表格中将dateacquired的值设置为可以为空的DateTime:

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; }
    }
}

另一个想法: 如果我不能将它设置为null,我怎样才能将它设置为DateTime?

1 个答案:

答案 0 :(得分:2)

我不确定我是否完全理解这个问题,你说如果输入的值为null,你想将它保存为DateTime.Now,如果不是,你想将它保存为输入的内容?在那种情况下,

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

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

这会尝试将输入的日期解析为有效的dateTime,如果不能,则inputDate将是最小的dateTime值。最后一行将DateAcquired设置为DateTime.Now如果无法解析enteredDate(您可以将其设置为您想要的任何内容),并且如果能够解析日期,则输入Date。