Link to home
Start Free TrialLog in
Avatar of Stacey Fontenot
Stacey Fontenot

asked on

How to deal with date input without values

I have an MVC C# Web Application where the user is not required to input a value in a date input field. If the user does not enter a date, MVC throws an error as it expecting a value. Below is my input code, model & controller information. What is the best way to handle if user does not supply a date and still insert data successfully into Sql using a stored procedure. The stored procedure is expecting a datetime as a parameter.

Controller Code -----------------------------------------------------------------------
        [HttpPost]
        [ActionName("AddTimeInfo")]
        public ActionResult AddTimeInfoPost(TimeInfo timeinfo)
        {
            if (ModelState.IsValid)
            {
                timeinfo.Created_By = Request.Cookies.Get("User_ID").Value;
                timeinfo.Updated_By = Request.Cookies.Get("User_ID").Value;
                try
                {
                    timeinfoDao.InsertTimeInfo(timeinfo);
                    TempData["Success"] = "true";
                }
                catch (Exception e)
                {
                    TempData["Success"] = "false";
                }
            }
            else
            {
                var errors2 = ModelState
                    .Where(x => x.Value.Errors.Count > 0)
                    .Select(x => new { x.Key, x.Value.Errors })
                    .ToArray();
                TempData["Success"] = "false";
            }
            return RedirectToAction("TimeInfo", "Home");
        }

Open in new window


chtml Code -----------------------------------------------------------------------
                <div class="row mg-t-20">
                    <label class="col-sm-5 form-control-label">Date Worked:</label>
                    <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                        <input type="date" name="Date Worked" id="add_Date_Worked" class="form-control" required/>
                    </div>
                    <label class="col-sm-1 form-control-label"><span class="tx-danger">*</span></label>
                </div>

Open in new window


Dapper SQL Insert Code -----------------------------------------------------------------------
        public void InsertTimeInfo(TimeInfo timeinfo)
        {
            string sqlQuery = @"EXEC dbo.[insTimeInfo] 
                                        @Date_Worked = @Date_Worked,
                                        @Created_By = @Created_By,
                                        @Updated_By = @Updated_By";

            Execute(sqlQuery, timeinfo);
        }

Open in new window


Model Code -----------------------------------------------------------------------
    public class TimeInfo
    {
        public DateTime Date_Worked { get; set; }
        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
    }
}

Open in new window

Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

set a default date value first then if the user doesn't enter a date use this value.

I have an MVC C# Web Application where the user is not required to input a value in a date input field. If the user does not enter a date, MVC throws an error as it expecting a value. Below is my input code, model & controller information. What is the best way to handle if user does not supply a date and still insert data successfully into Sql using a stored procedure.
In my thinking you must force the user to set a date or use the current date.. I would force the user to enter a date to ensure that you are not entering garbage into the database.
As rightly said, you can always pass a default date or send the value as Null
>>The stored procedure is expecting a datetime as a parameter.

Then if no date really is possible you also have to redesign the stored procedure (and possibly the table design) to cope.
I always use nullable types in such scenarios https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/ and on C#'s side, I do not think there is a better approach.

For your particular case the Date_Worked, is it something that user can set to any date? or it has to be when the actual record was created? If it is the later you could always insert datetime stamp via SQL itself rather than accepting it from the form. If it is not the case then, use nullable type in C# and handle it accordingly in the SP itself.
Try Date​Time.​Try​Parse or string.IsNullOrEmpty , and If you have a null value set timeinfo to some generic date like below. You can then exclude this value from queries or null it after passed to InsertTimeInfo. Also, you may want to use some client side checking. Maybe just give the input a generic date as a default value, plenty of stuff you can do with onmouseover and onfocus to clear the default text.

 DateTime fromDateValue;
            if (!DateTime.TryParse(timeinfo.Date_Worked.ToString(), out fromDateValue))
            {
                timeinfo.Date_Worked = DateTime.Parse("1001-01-01 01:01:01.001");
            }

Open in new window


E.G.
 public ActionResult AddTimeInfoPost(TimeInfo timeinfo)
        {
           DateTime fromDateValue;
            if (!DateTime.TryParse(timeinfo.Date_Worked.ToString(), out fromDateValue))
            {
                timeinfo.Date_Worked = DateTime.Parse("1001-01-01 01:01:01.001");
            }

            if (ModelState.IsValid)
            {
                timeinfo.Created_By = Request.Cookies.Get("User_ID").Value;
                timeinfo.Updated_By = Request.Cookies.Get("User_ID").Value;
                try
                {
                    timeinfoDao.InsertTimeInfo(timeinfo);
                    TempData["Success"] = "true";
                }
                catch (Exception e)
                {
                    TempData["Success"] = "false";
                }
            }
            else
            {
                var errors2 = ModelState
                    .Where(x => x.Value.Errors.Count > 0)
                    .Select(x => new { x.Key, x.Value.Errors })
                    .ToArray();
                TempData["Success"] = "false";
            }
            return RedirectToAction("TimeInfo", "Home");
        }


    }

Open in new window


Or a null check.

bool isnully = string.IsNullOrEmpty(timeinfo.Date_Worked.ToString()); 
if(isnully){ timeinfo.Date_Worked = DateTime.Parse("1001-01-01 01:01:01.001"); }

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.