c# - ASP.NET MVC 4 : Error received when trying to insert datetime field in Sql Server Database from input text box

标签 c# sql-server ajax asp.net-mvc error-handling

我正在使用一个Web应用程序,该应用程序将在单击时将数据插入表的一行中。当我尝试将日期插入数据库时​​,出现以下错误:

System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=Conversion failed when converting date and/or time from character string.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
以下字段是Sql Server表中的datetime列,即ProfileDate,CheckStartDatetime,LastCheckDate和CheckRecord。但是在模型中它们是字符串。我怀疑这是问题所在,因为当我显示sql表中的信息时会显示日期。
模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AlertNotificationWeb.Models
{
    public class Task
    {
        public int ID { get; set; }

        public string FunctionName { get; set; }

        public string FunctionDesc { get; set; }

        public string CheckPeriod { get; set; }

        public string Profiledate { get; set; }/*Represented as datetime in sql server table */

        public int PeriodDay { get; set; }

        public string AlertStatus { get; set; } 

        public string Comment { get; set; }

        public String LastCheckDate { get; set; } /*Represented as datetime in sql server table */

        public String CheckStartDatetime { get; set; } /*Represented as datetime in sql server table */

        public String CheckRecord { get; set; }/*Represented as datetime in sql server table */

    }
}
Controller :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using AlertNotificationWeb.Models;
using System.Data;
using System.Configuration;

namespace AlertNotificationWeb.Controllers
{
    public class TaskController : Controller
    {     
        //
        // GET: /Task/
        string connectionstring = @"data source=MSSQL4\MIS; initial catalog= datamart2; User ID= support_user; Password= support_user_pass";

        public ActionResult Index()
        {
            List<Task> tasks = new List<Task>();
            string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            string query = "SELECT [ID],[GroupSubsidiary],[FunctionName],[FunctionDesc],[CheckPeriod],[Profiledate],[AlertStatus], [CheckStartDatetime], [LastCheckDate] ,[Comment], [CheckRecord] FROM [datamart2].[dbo].[AS2_AlertsResults]";
            using (SqlConnection sqlcon = new SqlConnection(constr))
            {
                
                using (SqlCommand sqlcmd = new SqlCommand(query))
                {
                    sqlcon.Open();
                    sqlcmd.Connection = sqlcon;
                    
                    using (SqlDataReader sdr = sqlcmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {                                                        
                                tasks.Add(new Task
                                {
                                    ID = Convert.ToInt32(sdr["ID"]),
                                    GroupSubsidiary = Convert.ToString(sdr["GroupSubsidiary"]),
                                    FunctionName = Convert.ToString(sdr["FunctionName"]),
                                    FunctionDesc = Convert.ToString(sdr["FunctionDesc"]),
                                    CheckPeriod = Convert.ToString(sdr["CheckPeriod"]),
                                    Profiledate = Convert.ToString(sdr["Profiledate"]),
                                    AlertStatus = Convert.ToString(sdr["AlertStatus"]),
                                    CheckStartDatetime = Convert.ToString(sdr["CheckStartDatetime"]),
                                    LastCheckDate = Convert.ToString(sdr["LastCheckDate"]),
                                    Comment = Convert.ToString(sdr["Comment"]),
                                    CheckRecord = Convert.ToString(sdr["CheckRecord"])
                                });
                            
                            
                                
                            
                        }
                    }
                }
                    sqlcon.Close();
            }
                return View(tasks);
        }

            

        [HttpPost]
        public ActionResult UpdateTask(Task task)
        {
            //string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            
            string query = "UPDATE AS2_AlertsResults SET  AlertStatus= @AlertStatus, Comment= @Comment WHERE ProfileDate= @ProfileDate";
            using (SqlConnection sqlcon = new SqlConnection(connectionstring))
            {
                sqlcon.Open();
                SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
                sqlcmd.Parameters.AddWithValue("@ProfileDate", task.Profiledate);                 
                    sqlcmd.Parameters.AddWithValue("@AlertStatus", task.AlertStatus );
                    sqlcmd.Parameters.AddWithValue("@Comment", task.Comment );
                    sqlcmd.Connection = sqlcon;                    
                    sqlcmd.ExecuteNonQuery();
                    sqlcon.Close();
                

            }
            return new EmptyResult();

        }

        public ActionResult ArchiveResults(Task task)
        {
            
            string query = " INSERT INTO AS2_AlertsResultsArchive(ID ,ProfileDate, GroupSubsidiary, FunctionName, FunctionDesc, CheckPeriod, CheckStartDatetime, LastCheckDate,  AlertStatus,  Comment, CheckRecord) VALUES (@ID,@ProfileDate, @GroupSubsidiary, @FunctionName, @FunctionDesc,@CheckPeriod, @CheckStartDatetime, @LastCheckDate, @AlertStatus, @Comment, @CheckRecord)";
            using (SqlConnection sqlcon = new SqlConnection(connectionstring))
            {
                sqlcon.Open();
                SqlCommand sqlcmd = new SqlCommand(query,sqlcon);
                sqlcmd.Parameters.AddWithValue("@ID", task.ID);
                sqlcmd.Parameters.AddWithValue("@ProfileDate", DateTime.Parse(task.Profiledate));
                sqlcmd.Parameters.AddWithValue("@GroupSubsidiary", task.GroupSubsidiary);
                sqlcmd.Parameters.AddWithValue("@FunctionName", task.FunctionName);
                sqlcmd.Parameters.AddWithValue("@FunctionDesc", task.FunctionDesc);
                sqlcmd.Parameters.AddWithValue("@CheckPeriod", task.CheckPeriod);
                sqlcmd.Parameters.AddWithValue("@AlertStatus", task.AlertStatus);
                sqlcmd.Parameters.AddWithValue("@CheckStartDatetime", DateTime.Parse(task.CheckStartDatetime));
                sqlcmd.Parameters.AddWithValue("@LastCheckDate", DateTime.Parse(task.LastCheckDate));
                sqlcmd.Parameters.AddWithValue("@Comment", task.Comment);
                sqlcmd.Parameters.AddWithValue("@CheckRecord", DateTime.Parse(task.CheckRecord));
                sqlcmd.Connection = sqlcon;
                sqlcmd.ExecuteNonQuery();
                sqlcon.Close();

            }
            return new EmptyResult();
        }

    }
}
查看和jQuery/AJAX:(我有jQuery来的CheckRecord场更新到当过复选框被选中当前时间)
@using AlertNotificationWeb.Models
@model IEnumerable<Task>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>

    <meta name="viewport" content="width=device-width" />
    <title>Tasks List</title>
    <link href="~/Content/Tablestyles.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>
</head>
<body>
    <table id="tblTask" class="table" >
        <tr>
            <th>ID</th>
            <th>GroupSubsidiary</th>
            <th>FunctionName</th>
            <th>FunctionDesc</th>
            <th>CheckPeriod</th>
            <th>Profiledate</th>
            <th>CheckStartDatetime</th>
            <th>LastCheckDate</th>
            <th>AlertStatus</th>
            <th>Comment</th>
            <th>Status Updated</th>
        </tr>
        @foreach (Task task in Model)
        {
            <tr>
                <td class="taskID">
                    <span>@task.ID</span>
                </td>
                <td class="GroupSub">
                    <span>@task.GroupSubsidiary</span>
                </td>
                <td class="Fname">
                    <span>@task.FunctionName</span>
                    
                </td>
                <td class="Fdesc">
                    <span>@task.FunctionDesc</span>
                </td>
                <td class="Checkp">
                    <span>@task.CheckPeriod</span>
                </td>
                <td class="Pdate">
                    <span>@task.Profiledate</span>
                </td>
                <td class="checkstartdate">
                    <span>@task.CheckStartDatetime</span>
                </td>
                <td class="lastcheckdate">
                    <span>@task.LastCheckDate</span>
                </td>
                <td class="Status">
                    @if(task.AlertStatus.IsEmpty()) {                 
                        <input type="checkbox" value="NULL" id="checker"  />
                    }else{
                        <input type="checkbox" value="OK" id="checker2"  checked/>
                    }
                </td>
                <td class="Comment">
                    <span>@task.Comment</span>
                    <input type="text" value="@task.Comment" id="comz" style="display:none" />
                </td>
                <td class="CheckRecord">
                    <input type="text" id="crecords" value="@task.CheckRecord" />
                </td>
                <td>
                    
                    <a class="Save" href="javascript:;">Save</a>
                    <a class="Archive" href="javascript:;">Archive</a>
                    <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
                </td>
            </tr>
        }
    </table>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">


        //editing tasklist
        $("body").on("click", "#tblTask td", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }

            });

        });

        //updating tasklist
        $("body").on("click", "#tblTask .Save", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                }                               
                
            });
            row.find(".Edit").show();
            row.find(".Delete").hide();
            row.find(".Cancel").hide();
            //$(this).hide();
            //finding html elements  
            var alertval = $("#checker").val();
            var comval = $("#comz").val();
            var task = JSON.stringify({
                //ID: row.find(".taskID").find("span").html(),
                //GroupSubsidiary: row.find(".GroupSub").find("span").html(),
                //FunctionName: row.find(".Fname").find("span").html(),
                //FunctionDesc: row.find(".Fdesc").find("span").html(),
                //CheckPeriod: row.find(".Checkp").find("span").html(),
                Profiledate: row.find(".Pdate").find("span").html(),
                //PeriodDay: row.find(".Pday").find("span").html(),
                AlertStatus: row.find(".Status").find("input").val(),
                Comment: row.find(".Comment").find("span").html(),
            });
            $.ajax({
                type: 'POST',
                url: "@Url.Action("UpdateTask","Task")",
                data:  task,
                contentType: "application/json",
                dataType: "json",
                success: function () {
                    alert("Updated Sucessfully");
                },
                error: function () {
                    alert("An Error Occured");
                }
            });
            console.log(task);
        });
        


        $("body").on("click", "#tblTask .Status", function () {
            var timeclick = GetTodayDate();
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                var ass = row.find(".Status").find("input");
                var cm = row.find(".Comment").find("input");
                var dt = row.find(".CheckRecord").find("input");
                if ($(ass).prop("checked") == true) {
                    ass.val("OK");
                    cm.val("OK");
                    dt.val(timeclick);
                } else if ($(ass).prop("checked") == false) {
                    ass.val(null);
                    cm.val("Unchecked")
                    //row.find(".Status").find("span").html("Unchecked");
                }
            });

        });

        function GetTodayDate() {
            var today = new Date() ;
            var dd= today.getDate();
            var mm= today.getMonth();
            var yyyy = today.getFullYear();
            var hh = today.getHours();
            var min = today.getMinutes();
            var ss = today.getSeconds();
            var ms = today.getMilliseconds();
            var current = (mm + 1) + "/" + dd + "/" + yyyy+ " " + hh + ":" + min + ":" + ss + "." + ms;

            return current;
        }

        $("body").on("click", "#tblTask .Archive", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                }

            })
            row.find(".Edit").show();
            row.find(".Delete").hide();
            row.find(".Cancel").hide();
            //$(this).hide();
            //finding html elements  
            var alertval = $("#checker").val();
            var comval = $("#comz").val();
            var task = JSON.stringify({
                ID: row.find(".taskID").find("span").html(),
                GroupSubsidiary: row.find(".GroupSub").find("span").html(),
                FunctionName: row.find(".Fname").find("span").html(),
                FunctionDesc: row.find(".Fdesc").find("span").html(),
                CheckPeriod: row.find(".Checkp").find("span").html(),
                Profiledate: row.find(".Pdate").find("span").html(),
                PeriodDay: row.find(".Pday").find("span").html(),
                AlertStatus: row.find(".Status").find("input").val(),
                CheckStartDatetime: row.find(".checkstartdate").find("span").html(),
                LastCheckDate: row.find(".lastcheckdate").find("span").html(),
                Comment: row.find(".Comment").find("span").html(),
                CheckRecord: row.find(".CheckRecord").find("input").val(),
            });
            $.ajax({
                type: 'POST',
                url: "@Url.Action("ArchiveResults","Task")",
                data: task,
                contentType: "application/json",
                dataType: "json",
                success: function () {
                    alert("Updated Sucessfully");
                },
                error: function () {
                    alert("An Error Occured");
                }

            });
            console.log(task);
        });

      



    </script>


   
</body>
</html>
网页范例:
enter image description here
为什么即使我在 Controller 中使用DateTime.parse函数,也无法转换日期时间给我这个错误?

最佳答案

看来问题可能出在“状态更新”列?
Status Updated Field
尝试12:04,而不是12:4:26
对于空白,您也不想传递空白,而是要传递DbNull.Value实例来传递NULL值,因此可能需要进行一些转换。

关于c# - ASP.NET MVC 4 : Error received when trying to insert datetime field in Sql Server Database from input text box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65689387/

相关文章:

c# - 如何存储用于加密文件的 key

c# - 尚未为此应用程序配置 session 或使用 IHttpContextAccessor 时请求错误

c# - ServiceStack 4 是否保留收到的 HTTP 请求的日志?

C# 无法使用数组反序列化复杂的 Json 对象

java - 使用 JSON 进行 Ajax 调用时出现 400 错误

c# - 在 asp.net MVC 4 webapp 中,用户上传的文件存储在哪里?

sql-server - SQL Server XML 查询错误输出

sql-server - 通过 Powershell 部署 dacpac 导致错误 : "Unable to determine the identity of domain"

ajax - Grails:Ajax响应为空

javascript - 服务器响应多个异步 XHR