Home > other >  ASP.NET MVC (FX) Date values not showing up inside HTML.EditorFor from database model
ASP.NET MVC (FX) Date values not showing up inside HTML.EditorFor from database model

Time:09-17

In my ASP.Net MVC (FX) application I am saving 2 date values in this manor:

<div class="form-group">
                    @Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-4">
                        @Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @class = "datepicker" } })
                        @Html.ValidationMessageFor(model => model.Hire_Date, "", new { @class = "text-danger" })
                    </div>
                    <div style="margin-right:1%"><p style="color:#FF0000">*</p></div>
                </div>

...

<div class="form-group">
                    @Html.LabelFor(model => model.Injury_Date, "Injury Date", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-4">
                        @Html.EditorFor(model => model.Injury_Date, new { htmlAttributes = new { @class = "datepicker" } })
                        @Html.ValidationMessageFor(model => model.Injury_Date, "", new { @class = "text-danger" })
                    </div>
                    <div style="margin-right:1%"><p style="color:#FF0000">*</p></div>
                </div>

The model looks like this for that field:

[DataType(DataType.Date)]
public System.DateTime Hire_Date { get; set; }

[DataType(DataType.Date)]
public System.DateTime Injury_Date { get; set; }

And this saves to the database correctly. This data can also be retrieved and displayed on later screens, such as the Details.cshtml screen like this:

<dt>
            Hire Date
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Hire_Date)
        </dd>

        ......

        <dt>
            Injury Date
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Injury_Date)
        </dd>

details

Which is simple enough and makes sense, but on the Edit.cshtml page and a few others in which these date fields need to be editable, I can't figure out how I can display what the date value currently is to the user as well as give them the means to change it.

This is what I currently have in Edit.cshtml:

 <div class="form-group">
                @Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @class = "datepicker" } })
                    @Html.ValidationMessageFor(model => model.Hire_Date, "", new { @class = "text-danger" })
                </div>
                <div style="margin-right:1%"><p style="color:#FF0000">*</p></div>
            </div>

But as you can see this does not show the user what those date's currently are:

edit

Although they can change that value.

How can I both display the existing date(s) to the user while also allowing them to edit it?

EDIT 1:

I have updated the Edit.cshtml view to look like this:

 <div class="form-group">
                @Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @Value = @Model.Hire_Date.ToString("mm-dd-yyyy"), @class = "datepicker" } })
                    @Html.ValidationMessageFor(model => model.Hire_Date, "", new { @class = "text-danger" })
                </div>
                <div style="margin-right:1%"><p style="color:#FF0000">*</p></div>
            </div>

On both dates adding the @Value = @Model.Hire_Date.ToString("mm-dd-yyyy"), but this has not changed anything.

EDIT 2: I am including my Edit controller:

// GET: WC_Inbox/Edit/5
        public ActionResult Edit(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            WC_Inbox wC_Inbox = db.WC_Inbox.Find(id);
            if (wC_Inbox == null)
            {
                return HttpNotFound();
            }

            Employee employee = db.Employees.Find(wC_Inbox.EmployeeID);
            string fullName = employee.First_Name   " "   employee.Last_Name;
            string addUser = wC_Inbox.Add_User;
            ViewBag.EmployeeID = id;
            ViewBag.Name = fullName;
            ViewBag.Add_User = addUser;

            return View(wC_Inbox);
        }

// POST: WC_Inbox/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,InboxID,EmployeeID,District,Org_Number,Hire_Date,Job_Title,Work_Schedule,Injury_Date,Injury_Time,DOT_12,Start_Time,Injured_Body_Part,Side,Missing_Work,Return_to_Work_Date,Doctors_Release,Treatment,Injury_Description,Equipment,Witness,Questioned,Medical_History,Inbox_Submitted,Inbox_Reason,Comments,User_Email,Contact_Email,Specialist_Email,Optional_Email,Optional_Email2,Optional_Email3,Optional_Email4, Add_User")] WC_Inbox wC_Inbox)
        {
            if (ModelState.IsValid)
            {

                
                db.Entry(wC_Inbox).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var errors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in errors.ValidationErrors)
                        {
                            // get the error message 
                            string errorMessage = validationError.ErrorMessage;
                            System.Diagnostics.Debug.WriteLine(errorMessage);

                        }
                    }
                }
                return RedirectToAction("Index");
            }
            ViewBag.EmployeeID = new SelectList(db.Employees, "ID", "First_Name", wC_Inbox.EmployeeID);
            return View(wC_Inbox);
        }

EDIT 3:

This is how those date values are originally entered in the Create.cshtml page:

<div class="form-group">
                    @Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-4">
                        @Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @class = "datepicker" } })
                        @Html.ValidationMessageFor(model => model.Hire_Date, "", new { @class = "text-danger" })
                    </div>
                    <div style="margin-right:1%"><p style="color:#FF0000">*</p></div>
                </div>

CodePudding user response:

You need to set values as per following when you set property with [DataType(DataType.Date)]

@Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @Value = @Model.Hire_Date.ToString("mm-dd-yyyy"), @class = "datepicker" } })

CodePudding user response:

Since the editor is rendering an HTML date input, the value attribute needs to use the yyyy-MM-dd format for the browser to recognise it as a valid date. The browser will then take care of displaying the value to the user in the format they expect, depending on their language settings.

You could modify the EditorFor calls to specify the date format:

@Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { value = Model.Hire_Date.ToString("yyyy-MM-dd"), @class = "datepicker" } })

Or you could specify the format string on the model, and remove the value attribute from the EditorFor call:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime Hire_Date { get; set; }
@Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @class = "datepicker" } })

Or you could add a custom editor template in `~/Views/Shared/EditorTemplates/Date.cshtml':

@model DateTime?
@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    htmlAttrributes["type"] = "date";
}

@Html.TextBox("", Model?.ToString("yyyy-MM-dd"), htmlAttributes)
[DataType(DataType.Date)]
public System.DateTime Hire_Date { get; set; }
@Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { @class = "datepicker" } })
  • Related