1

I'm currently working on a ASP.NET MVC 3 project with use of Attributes on models to allow fast views creation (the attributes like [Required], [DisplayName("foo")] etc...)

In this project, i have some dates stored values formatted as string like "20120801" for example.

Is there a way to use the attribute :

[DisplayFormat(DataFormatString = "something")]  

or something else to transform YYYYMMDD to YYYY-MM-DD. In my example, showing on view "2012-08-01" instead of "20120801".

Thank's by advance !

1

2 Answers 2

2

You will need to update your model to look something like this:

public class Person
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-mm-dd}")]  
    public DateTime DateOfBirth { get; set; }
}

Your controller might need to parse the string first:

    public ActionResult Index()
    {
        Person p = new Person();
        p.DateOfBirth = DateTime.ParseExact("20120801","yyyyddmm",System.Globalization.CultureInfo.InvariantCulture);

        return View(p);
    }

And then to display it on your view, you will need to use something similar to the following code:

   <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.DateOfBirth)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DateOfBirth)
            @Html.ValidationMessageFor(model => model.DateOfBirth)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

For some reason the DisplayFormat attribute only seems to work with EditorFor and DisplayFor helpers.

Sign up to request clarification or add additional context in comments.

1 Comment

Si it's really not possible to make transformations on string values ?
0

I ended up with this solution

[ScaffoldColumn(false)]
public string MyValueFormattedAsYYYYMMDD { get; set; }

public string MyValueAsFormattedDate
{
    get
    {               
        return MyClassToTransform.MyTransformMethod(this.MyValueFormattedAsYYYYMMDD);
    }
}

With this method, i "scaffold" (hide) the column not formatted, and make a property with a getter to show the formatted string.

What do you think of this ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.