![](/img/trans.png)
[英]Html.TextBoxFor NullReferenceException using Razor syntax
[英]Represent string as currency or decimal using razor @Html.textboxfor
我有一个ASP.NET MVC应用程序。 我正在使用razor语法构建HTML表。 页面模型定义为
@model IEnumerable < DealView.Models.deal >
并且模型有一个属性
public string price { get; set; }
可以是数字或null。
我正在尝试获取用于显示逗号(即1,000,000)甚至更好的货币($ 1,000,000)的文本框。 目前我正在使用(1000000)
@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()
但认为null实例会导致问题。 任何建议表示赞赏。 如果要使用更好的帮助器函数,我不会嫁给TextBoxFor
。
如果可以更改类型,我将使用可为空的数字类型( int?
)。 然后,您可以使用内置格式 。
price.GetValueOrDefault(0).ToString("C0")
如果您无法更改字符串类型,请编写自定义的HtmlHelper扩展名以格式化字符串。
public static class HtmlHelperExtensions
{
public static string FormatCurrency(this HtmlHelper helper, string val)
{
var formattedStr = val; // TODO: format as currency
return formattedStr;
}
}
在您的意见中使用
@Html.FormatCurrency(price)
您可以首先解析字符串,以便视图模型为强类型数字(int,十进制等)。 我将使用可为空的decimal
。
public ActionResult MyAction()
{
string theThingToParse = "1000000";
ViewModel viewModel = new ViewModel();
if(!string.IsNullOrEmpty(theThingToParse))
{
viewModel.Price = decimal.parse(theThingToParse);
}
return View(viewModel);
}
为简单起见,您可以在视图模型中的属性上应用以下注释:
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public decimal? Price { get; set; }
现在,如果您在视图中使用EditorFor
,则应应用注释中指定的格式,并且值应以逗号分隔:
<%= Html.EditorFor(model => model.Price) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.