locked
Setting and storing time in MVC 5 time input field RRS feed

  • Question

  • User1151703306 posted

    Hi all,

    I have an MVC app.

    I make a call to a database, get my data in a dataset and store it in my class.

    Heres how im storing my data from the dataset

        public ActionResult Recovery()
        {
            List<PersonModel> lmd = new List<PersonModel>(); 
            DataSet ds = new DataSet();
            Connection.Connection con = new Connection.Connection();
            ds = con.mydata(); 
    
            foreach (DataRow dr in ds.Tables[0].Rows)  
            {
                lmd.Add(new PersonModel
                {
                    t_hrs = dr["hrs"] == DBNull.Value ? (DateTime?)null : (DateTime?)dr["hrs"],
                    sID = Convert.ToInt32(dr["sID"]),
                });
            }
    
            return View(lmd);
        }
    

    The field "hrs" that comes back from mysql is null and thats fine.

    When i try to store 11:11 hour:minute value in my "hrs" field the value is store correctly on the database.

    But when I return on webpage i get the following error:

    "System.InvalidCastException: 'Invalid cast specified.'"

    on controller this line

    lmd.Add(new PersonModel

    The time value memorized in database is 11:11:00.00000

    And type of field is

    `hrs` time(6) NULL DEFAULT NULL,
    

    I have tried, without success edit

    t_hrs = dr["hrs"] == DBNull.Value ? (DateTime?)null : (DateTime?)dr["hrs"],
    

    to

    t_hrs = dr["hrs"] == DBNull.Value ? (DateTime?)null : dr.Field<DateTime>("hrs"),
    

    How do fix this error?

    Thanks

    -       $exception  {"Invalid cast specified."} System.InvalidCastException
    +       Data    {System.Collections.ListDictionaryInternal} 
    System.Collections.IDictionary {System.Collections.ListDictionaryInternal} HResult -2147467262 int HelpLink null string + InnerException null System.Exception Message "Invalid cast specified." string Source "System.Data.DataSetExtensions" string StackTrace " in System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)\r\n
    in System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)\r\n
    in Ins.Controllers.HomeController.Recovery()
    in C:\\source\\repos\\Ins\\Ins\\Controllers\\HomeController.cs:line 439\r\n
    in lambda_method(Closure , ControllerBase , Object[] )\r\n
    in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)\r\n
    in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)\r\n
    in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)\r\n
    in System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)\r\n
    in System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)\r\n
    in System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()\r\n
    in System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)\r\n
    in System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0()\r\n
    in System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()" string + TargetSite {T ValueField(System.Object)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
    Sunday, January 10, 2021 6:26 PM

Answers

  • User-1545767719 posted

    What is Type of column "hrs" in the DataTable of the DataSet in question?

    I guess that the error occurs because the Type is neither "DataTime?" nor "DateTime".

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 10, 2021 10:32 PM
  • User1312693872 posted

    Hi,Golia

    "System.InvalidCastException: 'Invalid cast specified.'"

    You should check your data type, the 'hrs' in Database is 'Datetime' or others?

    Connection.Connection con = new Connection.Connection(); ds = con.mydata();

    what is the mydata() in your action, the problem may lies in the procedure you stored the data, Can you share this method?

    or you can use my demo to fill the data to DataSet from Database:

    public ActionResult Recovery()
            {
                SqlConnection conn = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=Golia1111;Integrated Security=SSPI;");
                conn.Open();
                SqlCommand cmd = new SqlCommand("Select sID,t_hrs FROM PersonModels", conn); 
                SqlDataAdapter sda = new SqlDataAdapter(cmd);  
                DataSet ds = new DataSet();
                sda.Fill(ds);
                List<PersonModel> lmd = new List<PersonModel>();
    
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    lmd.Add(new PersonModel
                    {
                        t_hrs = dr["t_hrs"] == DBNull.Value ? (DateTime?)null : (DateTime?)dr["t_hrs"],
                        sID = Convert.ToInt32(dr["sID"]),
                    });
                }
    
                return View(lmd);
            }

    Result:

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 11, 2021 3:15 AM

All replies

  • User-474980206 posted

    If you use the debugger you can see what data type dr[“hrs”] is and why the cast fails.

    Sunday, January 10, 2021 7:47 PM
  • User1151703306 posted

    If you use the debugger you can see what data type dr[“hrs”] is and why the cast fails.

    I have posted the debug error

    Sunday, January 10, 2021 8:39 PM
  • User-1545767719 posted

    What is Type of column "hrs" in the DataTable of the DataSet in question?

    I guess that the error occurs because the Type is neither "DataTime?" nor "DateTime".

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 10, 2021 10:32 PM
  • User1312693872 posted

    Hi,Golia

    "System.InvalidCastException: 'Invalid cast specified.'"

    You should check your data type, the 'hrs' in Database is 'Datetime' or others?

    Connection.Connection con = new Connection.Connection(); ds = con.mydata();

    what is the mydata() in your action, the problem may lies in the procedure you stored the data, Can you share this method?

    or you can use my demo to fill the data to DataSet from Database:

    public ActionResult Recovery()
            {
                SqlConnection conn = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=Golia1111;Integrated Security=SSPI;");
                conn.Open();
                SqlCommand cmd = new SqlCommand("Select sID,t_hrs FROM PersonModels", conn); 
                SqlDataAdapter sda = new SqlDataAdapter(cmd);  
                DataSet ds = new DataSet();
                sda.Fill(ds);
                List<PersonModel> lmd = new List<PersonModel>();
    
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    lmd.Add(new PersonModel
                    {
                        t_hrs = dr["t_hrs"] == DBNull.Value ? (DateTime?)null : (DateTime?)dr["t_hrs"],
                        sID = Convert.ToInt32(dr["sID"]),
                    });
                }
    
                return View(lmd);
            }

    Result:

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 11, 2021 3:15 AM