0

Straightaway. In my model I have a field DistanceTravelled , it is of type double. Now whenever i want to display it using @Html.DisplayFor helper method, then I want the distance travelled value to be appended by "Km". For Example:

123 Km instead of 123

I can do that by placing Km at the end of @Html.DisplayFor helper. But I was hoping that there must be some data annotation attribute or some other simpler way.

Thanks for trying to help. :)

2 Answers 2

2

You can modify your ViewModel to something like this:

...
string DistanceTravelled {{ get { return String.Format("{0} km",this.DistanceTravelled; };set; }
...

But I think this won't work with your Doulble. Implicit convention between Double and string :(

Ok got it :)

In view model:

using System.ComponentModel.DataAnnotations;
+
[DisplayFormat(DataFormatString="{0}km")]
double DistanceTravelled {get;set;}

and this code below for Id=2:

@Html.DisplayFor(m=>m.Id)

renders as

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

1 Comment

Good idea. Any idea with data annotations? DisplayFormat?
1

You could use

[DisplayFormat(DataFormatString="{0} km")]
public double DistanceTravelled {get;set;}

More info about the DisplayFormatAttribute: DisplayFormatAttribute Class

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.