简体   繁体   English

ASP.NET MVC 4:尝试从输入文本框在 Sql 服务器数据库中插入日期时间字段时收到错误

[英]ASP.NET MVC 4: Error received when trying to insert datetime field in Sql Server Database from input text box

I am working on a web application that will insert data into a row in a table when clicked.我正在开发一个 web 应用程序,该应用程序将在单击时将数据插入表中的一行。 When I try to insert the date into the database I get the following error:当我尝试将日期插入数据库时,出现以下错误:

System.Data.SqlClient.SqlException was unhandled by user code System.Data.SqlClient.SqlException 未被用户代码处理
HResult=-2146232060 H结果=-2146232060
Message=Conversion failed when converting date and/or time from character string. Message=从字符串转换日期和/或时间时转换失败。
Source=.Net SqlClient Data Provider Source=.Net SqlClient 数据提供者
ErrorCode=-2146232060错误代码=-2146232060
Class=16班级=16

The following fields are datetime columns in the Sql Server tabl,e ProfileDate, CheckStartDatetime, LastCheckDate and CheckRecord.以下字段是 Sql 服务器表中的日期时间列,e ProfileDate、CheckStartDatetime、LastCheckDate 和 CheckRecord。 However in the model they are string.但是在 model 中,它们是字符串。 I doubt this is the issue since when I display information from the sql table the dates are displayed.我怀疑这是问题所在,因为当我显示 sql 表中的信息时,会显示日期。

Model: Model:

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: 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();
        }

    }
}

View and Jquery/Ajax: (I have jquery to update the CheckRecord field to the current time when ever the checkbox is checked)查看和 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>

Sample of Webpage:网页样本:

在此处输入图像描述

Why is it failing to convert the datetime giving me this error even after I use the DateTime.parse function in the controller?为什么即使我在 controller 中使用 DateTime.parse function 后,它仍无法转换日期时间给我这个错误?

It seems like the issue may come from the Status Updated column?看起来问题可能来自状态更新列?

状态更新字段

Try 12:04, not 12:4:26尝试 12:04,而不是 12:4:26

And also for blank, you don't want to pass blank but DbNull.Value instance instead to pass up a NULL value, so some conversion may be necessary.而且对于空白,您不想传递空白而是传递 DbNull.Value 实例来传递 NULL 值,因此可能需要进行一些转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从文本框中插入数据库asp.net MVC4 - Insert Data from text box to database asp.net MVC4 从ASP.NET将Datetime.now插入SQL Server - Insert Datetime.now from asp.net into sql server 尝试使用asp.net Web应用程序将数据插入SQL Server数据库,出现错误 - Trying to insert data into SQL Server database using asp.net web application, getting an error ASP.NET-填写字段并单击按钮后,将数据插入SQL Server数据库吗? - ASP.NET - Insert data into an SQL server database when a field has been filled in and a button clicked? 从ASP.NET将数据插入本地SQL Server数据库 - Insert data into local SQL Server database from ASP.NET 如何以列表形式从数据库中检索文本(SQL Server和ASP.NET MVC) - How do I retrieve text from database in list form (SQL Server & ASP.NET MVC) SQL Server数据库中ASP.NET MVC中的Bootstrap滑块 - Bootstrap slider in ASP.NET MVC from SQL Server database ASP.NET MVC 4:对 controller 进行 Ajax 调用以更新 Z9778840A0100CB30C982228B7 数据库时出错 - ASP.NET MVC 4: error when making Ajax call to controller to update SQL Server database 将记录从asp.net插入SQL Server数据库期间出错 - Error during insert of record from asp.net into SQL Server database 如何从隐藏表单输入到数据库 MySQL 在 ASP.NET MVC 中输入 DateTime Now? - How to input DateTime Now in ASP.NET MVC from the hidden form input to database MySQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM