2011-11-01 54 views
1

我有一个可编辑页面,我想重新格式化大部分字段,假设我有2个字段,里程和价格。 我需要TextBoxFor显示它们MVC中的Dispaly格式与剃刀不显示正确

Model.cs

public class TestModel { 
    [DisplayName("Mileage: ")] 
    [DisplayFormat(DataFormatString = "{0:##,###,###}")] 
    [RegularExpression(@"^(?:\d+|\d{1,3}(?:,\d{3})*)$", ErrorMessage = "*")] 
    public Int32 Mileage { get; set; } 

    [DisplayName("Price: ")] 
    [DataType(DataType.Currency)] 
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)] 
    public Int32 Price{ get; set; } 
} 

Controller.cs

public ActionResult Index() { 
     var model = new TestModel(); 
     model.Mileage=150000; 
     model.Price=21900; 
     return View(model); 
    } 

Index.cs

@using (Html.BeginForm()) { 
@Html.TextBoxFor(m => m.Mileage, new { @class = "w200" }) 
@Html.TextBoxFor(m => m.Price, new { @class = "w200" }) 
<input type="submit" /> 

}

的Un幸运的是我没有看到格式化的价格和里程数。

任何帮助,尽快将意识到,

回答

3

设置ApplyFormatInEditModetrue

[DisplayFormat(DataFormatString = "{0:##,###,###}", ApplyFormatInEditMode=true)] 

你也可以切换到EditorFor而不是TextBoxFor只是在MVC的最佳实践方面,但其与您的问题无关。

+0

我试过了,但它给出了以下例外:“传入字典的模型项目类型为”System.Int32“,但此字典需要类型为”System.String“的模型项目。 –

+0

@AlaaOsta你的意思是EditorFor的东西,或ApplyFormatInEditMode? –

+0

它似乎是EditorFor的东西,如果我将其更改为TextBoxFor页面将加载正常,但该值根本没有格式化。 –