简体   繁体   中英

ToString(“C”) formatting fails in ASP.NET MVC Partial View in VB.NET 2013

This line

@Model.CurrentPrice.ToString("C") 

works in C# 2013 , but fails in VB.NET with invalidcast exception .

The CurrentPrice property is a nullable decimal .

I've had to do this as a fix:

@CType(Model.CurrentPrice, Model.CurrentPrice.GetType()).ToString("c")

Any idea of why @Model.CurrentPrice.ToString("C") does not work in VB.NET 2013 and how to fix this instead of doing the above conversion?

Thanks, Jean

What are you expecting that line of code to produce if CurrentPrice is Nothing ? Unless you're 100% sure that it will always have a value, you would need to explicitly handle both cases, eg

@If(Model.CurrentPrice.HasValue,
    Model.CurrentPrice.Value.ToString("C"),
    String.Empty)

You can replace that String.Empty with something else if you want something else when there's no value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM