eka808
eka808

Reputation: 2317

DisplayFormat Model attribute to transform string values

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 !

Upvotes: 1

Views: 2641

Answers (2)

Deano
Deano

Reputation: 2895

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.

Upvotes: 2

eka808
eka808

Reputation: 2317

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 ?

Upvotes: 0

Related Questions