c#中用于强类型视图的字符串格式化
本文关键字:字符串 格式化 视图 强类型 用于 | 更新日期: 2023-09-27 18:02:30
我想知道如何将强类型视图价格字段转换为2位说明符,就像我在数据库中有一个货币字段,例如15转换为15.000,我只是想在视图中显示15.00,下面是代码:
<%: Html.TextBoxFor(model =>model.Price, new { maxlength = "5", style = "width:40px;" })%>
我尝试了如下操作,但没有成功:
<%: Html.TextBoxFor(model => String.Format("{0:n}"model.Price), new { maxlength = "5", style = "width:40px;" })%>
您可以在模型上添加如下属性:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:n}")]
如果你不想这样做,那么你需要使用"old"样式的文本框:
<%= Html.TextBox("Price", string.Format("{0:n}", Model.Price)) %>
试试这个:
<%: Html.TextBoxFor(model => model.Price.ToString("0.00"), new { maxlength = "5", style = "width:40px;" })%>
更新:你还在你的原始语法中遗漏了一个逗号,这也可能是所有阻止它以这种方式工作的原因。应该是:
<%: Html.TextBoxFor(model => String.Format("{0:n}", model.Price), new { maxlength = "5", style = "width:40px;" })%>
同样,对于小数点后2位,试着这样写:
<%: Html.TextBoxFor(model => String.Format("{0:0.00}", model.Price), new { maxlength = "5", style = "width:40px;" })%>
最好的方法是在视图模型上使用DataAnnotations显示格式属性。像这样:
[DisplayFormat (DataFormatString = {0: n}))
然后使用Html。EditorFor(model => model. price)来呈现输入
您是否尝试过使用mode.Price.ToString()
并在ToString方法中指定所需的格式字符串?
这可能有帮助。
private DateTime hDay;
[DisplayName("Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime HireDate
{
get
{
if (hDay == DateTime.MinValue)
{
return DateTime.Today;
}
else
return hDay;
}
set
{
if (value == DateTime.MinValue)
{
hDay = DateTime.Now;
}
}
}
或
我们也可以这样用
@Html.TextBoxFor(m => m.MktEnquiryDetail.CallbackDate, "{0:dd/MM/yyyy}")