Skip to content Skip to sidebar Skip to footer

Represent String As Currency Or Decimal Using Razor @html.textboxfor

I have an ASP.NET MVC App. I am building an HTML table using razor syntax. The page model is defined as @model IEnumerable < DealView.Models.deal > and the model has a prope

Solution 1:

You could firstly parse the string so the view model is a strongly typed number (int, decimal, etc). I'll use a nullable decimal.

public ActionResult MyAction()
{
    string theThingToParse = "1000000";
    ViewModel viewModel = new ViewModel();

    if(!string.IsNullOrEmpty(theThingToParse))
    {
        viewModel.Price = decimal.parse(theThingToParse);    
    }

    return View(viewModel);
}

For simplicity you could apply the following annotation on the property in your view model:

[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
publicdecimal? Price { get; set; }

Now if you use EditorFor in your view the format specified in the annotation should be applied and your value should be comma separated:

<%= Html.EditorFor(model => model.Price) %>

Solution 2:

If you can change the type I'd use a nullable numeric type (int?). Then you can use the built-in formats.

price.GetValueOrDefault(0).ToString("C0")

If you can't change the string type then write a custom HtmlHelper extension to format your strings.

publicstaticclassHtmlHelperExtensions
{
    publicstaticstringFormatCurrency(this HtmlHelper helper, string val)
    {
        var formattedStr = val;  // TODO: format as currencyreturn formattedStr;
    }
}

Use in your views

@Html.FormatCurrency(price)

Post a Comment for "Represent String As Currency Or Decimal Using Razor @html.textboxfor"