开发者

How to pass a currency formatted string from the controller to the view?

I have a formatted string variable to which passing to a ViewData Variable. My Controller basically looks like this:

if(ModelState.IsValid)
{
    string total = "$2.00";
    ViewData["totalSales"] = total;
    return View();
}

I have an html helper function in my view like this:

<%: Html.Label(ViewData["totalSales"].Tostring()) %>

however the asp.net mvc engine is generating this :

<label for="$2_00">00</label>

I just wanna pass the money value to the view and display it. It appears that the decimal is breaking the value. However there has got to be a way around this. Am I making a noob mistake here ?


Well I was able to bypass this by doing this:

<p><%: ViewData["totalSales"].ToString() %> </p>

But this does not explain why a decimal in a str开发者_如何学Going is causing data loss. Any ideas ?


pass your total variable as a decimal:

decimal total = 2.0;
ViewData["totalSales"] = total;
return View();

then in your view, render the label like this:

<%: Html.Label(string.Format("{0:C2}", ViewData["totalSales"])) %>


Use String.Format() with currency

Your mistake is that the framework will automatically escape/transform special characters (such as the ".") when they're turned into HTML attributes. That's by design.

Also, why are you passing a hard coded string via ViewData? Is that computed from your models? You may not be using Label correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜