[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Format Date in View Model DisplayFor and EditorFor

Posted on 2014-04-22
19
Medium Priority
?
8,592 Views
Last Modified: 2014-05-20
I had a question on Forums.Asp.Net that asked
"The Format date in view Model at  http://forums.asp.net/t/1945089.aspx?Format+Date+in+view+model tells how to add an attribute to a date property in the model like below to get it to display as a Date only. However I am wondering if this is done with an Entity Framework Database First Model, will this be maintained after you do an Update From Database?"
The code I am referring to is here:
Display(Name = "Start Date")]
        [Required(ErrorMessage = "Please enter a start date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public string startDate { get; set; }

Open in new window

I was told to use the Metadata files so eventually I changed the meta data files as below
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web.Mvc;

namespace VFS_ProcurementTracking.Models
{
    [MetadataType(typeof(prc_RequirementMetaData))]
    public partial class prc_Requirement
    {
        internal sealed class prc_RequirementMetaData
        {
            private prc_RequirementMetaData()
            {
            }
        }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public Nullable<System.DateTime> CustomerRDD { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public System.DateTime Import_CreateDate { get; set; }
    }
}

Open in new window


However the EditorFor's and DisplayFor's did not display the specified format.  does anyone see what I am doing incorrectly and provide guidance?  It is important to note that both of those fields have JQueryUI datepickers attached so that it is important that it can read the entry as a date.
0
Comment
Question by:Edward Joell
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 13
  • 4
19 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40016955
How are you outputting the value in your view? The strongly typed editors (i.e. TextBoxFor, etc) don't support the DataFormatString, whereas the more general EditorFor does
0
 

Author Comment

by:Edward Joell
ID: 40017383
I am using EditorFor and DisplayFor.  I am insufficiently experienced to play around with tools other than those two and dropDownlistfor.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40017418
Your metadata properties should be inside the metadata class. Like:
namespace VFS_ProcurementTracking.Models
{
    [MetadataType(typeof(prc_RequirementMetaData))]
    public partial class prc_Requirement
    {
        internal sealed class prc_RequirementMetaData
        {
            private prc_RequirementMetaData()
            {
            }
 
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
            public Nullable<System.DateTime> CustomerRDD { get; set; }

            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
            public System.DateTime Import_CreateDate { get; set; }
        }
    }
}

Open in new window

If that still doesn't work, can you post the code for your View too.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:Edward Joell
ID: 40017431
Maybe my eyes aren't working properly. However, I fail to see how that differs from the code I posted above.  Can someone point out what I am missing?
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40017444
In your original post you have the Metadata properties outside of your metadata class. The revised version moves the closing brace of the metadata class down, so that it incorporates the properties.

So basically the brace at line 20 in your original post is now at line 17 of the revised version.
0
 

Author Comment

by:Edward Joell
ID: 40017821
Great.  i will try that.
0
 

Author Comment

by:Edward Joell
ID: 40017988
I set up the meta data like this
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web.Mvc;

namespace VFS_ProcurementTracking.Models
{
    [MetadataType(typeof(prc_RequirementMetaData))]
    public partial class prc_Requirement
    {
        internal sealed class prc_RequirementMetaData
        {
            private prc_RequirementMetaData()
            {
            }
        

            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
            public Nullable<System.DateTime> CustomerRDD { get; set; }

            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
            public System.DateTime Import_CreateDate { get; set; }
        }
    }
}

Open in new window


It made no difference.   Both date and time are shown in EditorFor and DisplayFor.  
Same fields different issue.  The one field is nullable but the other is not.  So when an empty "Create" view is shown, the editorfor is showing 01/01/0001 12:00:00 AM.  I would like that to show the current date and only the date by default.  How can I do that.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40019456
Is your prc_Requirement class in the same namespace as the underlying Entity Framework class?

The code you have is technically correct for what you are trying to do, so the issue may be that it is treating your class as separate from the underlying entitiy.
0
 

Author Comment

by:Edward Joell
ID: 40019793
yes
0
 

Author Comment

by:Edward Joell
ID: 40050420
As state above the the prc_Requirement class is in the same namespace.  So what would be treating my class as separate from the underlying entity, and why?
0
 

Author Comment

by:Edward Joell
ID: 40067862
Here is a thought
The model being displayed in the view contains a property of type "prc_Requirement" above.  Maybe, it is not enough to set the DisplayFormat in metadata for the "prc_Requirement model" but in metadata for the "RequirementViewShowingModel" as well?
0
 

Author Comment

by:Edward Joell
ID: 40067908
But the question is since the fields CustomerRDD and Import_ExportDate are in the Requirements Model I do I refer to them in the Metadata file?  Just setting them with there own names did not work as the view could not find the fields for which the metadata was created.  Referring to them as Requirement.CustomerRDD  and Requirement.Import_ExportDate did not work because of compile time errors.
0
 

Assisted Solution

by:Edward Joell
Edward Joell earned 0 total points
ID: 40068533
Rachel Appel solved everything with her blog here Rachel Appel solved everything with her blog here http://rachelappel.com/create-user-friendly-date-fields-with-asp.net-mvc-editortemplates-amp-jqueryui  about using templates.
0
 

Author Comment

by:Edward Joell
ID: 40068550
I've requested that this question be closed as follows:

Accepted answer: 0 points for Joeller's comment #a40068533

for the following reason:

This works excellently.  CUDOS to Rachel Appel
0
 

Author Comment

by:Edward Joell
ID: 40068551
Need to Undo this as solved because the templates do not work on the Create view because at that time the Model's DateTime property is null and the template caused an error "The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'."  So I need a way for this to work in the create View
0
 

Accepted Solution

by:
Edward Joell earned 0 total points
ID: 40068602
At stackoverflow.com/questions/4249955/mvc-3-editor-template-with-datetime I found the solution I changed Rachel's template from
@model DateTime

@Html.TextBox("", String.Format("{0:d}", Model.Date.ToShortDateString()))

Open in new window


To
@model DateTime?
@Html.TextBox("", String.Format("{0:d}", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty) ))

Open in new window


And that fixed everything
0
 

Author Closing Comment

by:Edward Joell
ID: 40077104
Kudos to StackOverflow's Fabian, and Rachel Appel
0

Featured Post

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question