再present字符串使用剃刀@ Html.textboxfor货币或小数 [英] Represent string as currency or decimal using razor @Html.textboxfor

查看:150
本文介绍了再present字符串使用剃刀@ Html.textboxfor货币或小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序。我建立使用剃刀语法HTML表格。页面模型定义为

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 >

和模型有一个属性。

public string price { get; set; }

其可以是数字或空

which can be a number or null.

我试图让文本框的显示逗号(即1,000,000),甚至更好的货币($ 1,000,000)。此刻,我刚开始使用(1000000)

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>
    }

我曾尝试 item.price.asint()想起了空实例导致问题。任何的建议是AP preciated。我没有结婚到 TextBoxFor 如果使用更好的辅助函数。

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.

推荐答案

您可以先解析字符串,视图模型是一个强类型的号码(INT,小数等)。我将使用一个可空小数

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; }

现在,如果你使用 EditorFor 在视图中的注释指定的格式应适用与你的价值应以逗号分隔的:

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) %>

这篇关于再present字符串使用剃刀@ Html.textboxfor货币或小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆