Maneksh Veetinal
Maneksh Veetinal

Reputation: 143

Set DataFormatString in Annotations from a Global Variable

Suppose if I have an Annotation like the following

[DisplayFormat(DataFormatString = "{0:#.00#}", ApplyFormatInEditMode = true)]

It works great. But suppose I want to replace the DataFormatString in real time i.e. some times like this {0:#.00#} and sometimes {0:#.000#} based on some application settings the user chooses. Is there a way to do that?

I tried storing the format string in a global variable, but it gives me the following error.

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

If I make the global variable constant it works but then the purpose is lost. Any advice on a work around?

Basically I would like to give the users an option to set the decimal spaces universally with out having to implement the feature on a per View/Controller basis.

I know I can put the culture using NumberFormat.CurrencyDecimalDigits. But this will ignore Zeros after the decimal.

Upvotes: 0

Views: 979

Answers (2)

Dima
Dima

Reputation: 6741

There is a good library called MvcExtensions, one of it's feature is fluent metadata configuration. It allows you to construct model metadata fluently instead of DataAnnotations. Using this library, you may accomplish your task:

Configure(x => x.Payment)
  .Format(() => ConfigurationManager.DataFormatString)

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Attribute requires constant string, you can't change that. Also this attribute does not provide ability to provide resource name. So, I think best way to you is creating DisplayTemplate and EditorTemplate for this property.

[UIHint("Bar")]
public decimal Bar { get; set; }

And in Bar template you can change format based on some application settings chosen by user:

@model decimal

@Model.ToString(HttpContext.Current.Session["format"].ToString())

Upvotes: 1

Related Questions