Represent string as currency or decimal using razor @Html.textboxfor

橙三吉。 提交于 2020-01-04 06:28:42

问题


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.


回答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)]
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) %>



回答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.

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)


来源:https://stackoverflow.com/questions/21419017/represent-string-as-currency-or-decimal-using-razor-html-textboxfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!