wbm
wbm

Reputation: 155

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 property

public string price { get; set; }

which can be a number or null.

I am trying to get the textbox for to show comma's (ie 1,000,000) or even better currency ($1,000,000). At the moment I am just getting (1000000) using

@foreach (var item in Model)
    {
        <tr>
            ...
            <td>@Html.TextBoxFor(modelItem => item.price, new { id = string.Format("
                   {0}_price", item.ID) })</td>
            ...
        </tr>
    }

I have tried item.price.asint() but think the null instances causes problems. Any advice is appreciated. I am not married to the TextBoxFor if there is a better helper function to use.

Upvotes: 2

Views: 14595

Answers (2)

David Spence
David Spence

Reputation: 8079

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)]
public decimal? 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) %>

Upvotes: 2

Jasen
Jasen

Reputation: 14250

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.

public static class HtmlHelperExtensions
{
    public static string FormatCurrency(this HtmlHelper helper, string val)
    {
        var formattedStr = val;  // TODO: format as currency
        return formattedStr;
    }
}

Use in your views

@Html.FormatCurrency(price)

Upvotes: 2

Related Questions