Note that there are some explanatory texts on larger screens.

plurals
  1. POPercentage properties in MVC 3
    text
    copied!<p>My application has many models, many of which contain percentage data. These are represented as <code>decimal</code> or <code>decimal?</code> structs in the model. However, not all properties with <code>decimal</code> structs are percentages. Some should be treated like regular decimals.</p> <p>The percentages need special attention:</p> <ul> <li>For display, they should use <code>{0:P2}</code> format. (I have this part working.)</li> <li>For editing, they should allow the same format as the display, i.e. "95" or "95%" or "95.00 %" all bind to a value of 0.95.</li> </ul> <p>I started down the road of creating a <code>PercentModelBinder</code> that implements <code>IModelBinder</code>, but then realized that you can only apply the <code>ModelBinderAttribute</code> to a <em>class</em>, not a property.</p> <p>What's the best way to handle this case where <em>some</em> (but not all) uses of a type need special handling both for display and binding?</p> <p>Every solution I think of smells badly of overkill, fighting the MVC framework. Surely there is a better way than:</p> <ul> <li>Creating a custom <code>Percentage</code> struct and using it as the basis for the IModelBinder and EditorTemplates, or </li> <li>Reimplementing the default binding behavior of <code>decimal</code> and <code>decimal?</code> and changing the parsing logic based on intimate knowledge of my model, or</li> <li>Implementing a custom model binder for each class that contains a percentage property, or</li> <li>Using fake proxy properties in the model (i.e. breaking MVC)</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload