c# - 在 mvc3 上保存 null DateTime

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

我在 sql 中保存日期时间时遇到问题。我的问题是我想保存具有空值的日期时间。谁能帮我解决这个问题吗?

这是我的代码:

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>

我的保存 Controller :

[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?

最佳答案

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

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

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

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

关于c# - 在 mvc3 上保存 null DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599824/

相关文章:

asp.net-mvc-3 - jquery.validate.unobtrusive 不适用于动态注入(inject)元素

c# - 使用通用存储库将 autofac 与 webapi 绑定(bind)

c# - 当我使用 MVVM 模型时,如何在 WPF 中使用 WndProc?

c# - 如何在C#中从两个不同的应用程序访问串行端口

Mysql自定义where条件

sql - 选择给定时间间隔的行

asp.net-mvc-3 - 自定义 WebPageRazorHostFactory

c# - 在 asp.net 转发器控件中执行数学计算

sql - postgres根据条件执行存储过程

asp.net-mvc-3 - 动态加载部分 View