【问题标题】:Using Editor template for varying display使用编辑器模板进行不同的显示
【发布时间】:2011-02-02 19:13:56
【问题描述】:

我必须将我的小数显示为 00.00。我有以下 EditorTemplate

 @model Decimal?

@if (Model.HasValue)
{
   @Model.Value.ToString("00.00");
 }

我还必须在文本框和标签中显示小数点。如何使用上述模板以所需格式显示以下内容。

@Html.TextBoxFor(m=>@item.Price)
 @Html.LabelFor(m=>@item.Price)

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    您可以在模型上使用[DisplayFormat] 属性:

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:00.00}", NullDisplayText = "")]
    public decimal? Price { get; set; }
    

    然后显示:

    @Html.DisplayFor(x => x.Price)
    

    编辑:

    @Html.EditorFor(x => x.Price)
    

    【讨论】:

    • 使用 @EditorFor 它仍然显示为标签而不是文本框
    • @user281180,这可能是因为您有一些用于小数类型的自定义编辑器模板,不是吗?
    【解决方案2】:

    创建一个 Views\Shared\EditorTemplates 文件夹下的 Decimal.ascx

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<decimal?>" %>
    <% 
    Html.LabelFor(m => m);
    Html.TextBox (ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty), 
    

    Model.HasValue ? Model.Value.ToString("00.00") : "00.00", 新的 {readonly = "readonly"}) %>

    如果您只需要显示它,在这种情况下切换显示编辑器(DisplayTemplates、DisplayFor 等) readonly 属性是使文本框只读(不可编辑)

    【讨论】:

      【解决方案3】:

      您可以在模板中使用

      @Html.TextBox("", (Model.HasValue ? Model.Value.ToString("00.00") : String.Empty))
      

      @if (Model.HasValue) {
        @Model.Value.ToString("00.00");
        @Html.TextBox("", Model.Value.ToString("00.00"))
      }
      

      那么在你看来使用

      @Html.EditorFor(m => m.Price)%>
      

      【讨论】:

      • 使用我提供的代码,我可以很好地处理文本框。位如何使用 labelFor 和 TexboxFor 做到这一点?
      • 使用@Html.EditorFor() 在你的视图中显示模板
      猜你喜欢
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2011-07-22
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      相关资源
      最近更新 更多