2011-03-02 80 views
3

我在我的MVC应用程序,其具有所谓的单价属性有一个模型(罗斯文):MVC模型绑定+格式化

public class Product { 
    public decimal UnitPrice { get; set; } 
} 

我认为,我想显示此货币{0:C}。我尝试使用DataAnnotations DisplayFormatAttribute:http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx

它的工作正常显示的目的,但是当我尝试和POST它阻止我提交,因为它不是正确的格式。如果我删除$,那么它会允许我。

有什么办法,我可以把它忽略格式试图验证什么时候?

+0

您使用ApplyFormatInEditMode =真的吗? – swapneel 2011-03-02 15:59:02

+0

是的。我正在使用它。 – Dismissile 2011-03-02 16:12:25

回答

4

你可以写为Product类型的定制模型绑定和手动解析值。这里是你如何才能够着手:

型号:

public class Product 
{ 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:C}")] 
    public decimal UnitPrice { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new Product { UnitPrice = 10.56m }); 
    } 

    [HttpPost] 
    public ActionResult Index(Product product) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(product); 
     } 
     // TODO: the model is valid => do something with it 
     return Content("Thank you for purchasing", "text/plain"); 
    } 
} 

查看:

@model AppName.Models.Product 
@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(x => x.UnitPrice) 
    @Html.EditorFor(x => x.UnitPrice) 
    @Html.ValidationMessageFor(x => x.UnitPrice) 
    <input type="submit" value="OK!" /> 
} 

模型绑定(这里的神奇在哪里都会发生):

public class ProductModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var price = bindingContext.ValueProvider.GetValue("unitprice"); 
     if (price != null) 
     { 
      decimal p; 
      if (decimal.TryParse(price.AttemptedValue, NumberStyles.Currency, null, out p)) 
      { 
       return new Product 
       { 
        UnitPrice = p 
       }; 
      } 
      else 
      { 
       // The user didn't type a correct price => insult him 
       bindingContext.ModelState.AddModelError("UnitPrice", "Invalid price"); 
      } 
     } 
     return base.BindModel(controllerContext, bindingContext); 
    } 
} 
01在

注册模型绑定的:

ModelBinders.Binders.Add(typeof(Product), new ProductModelBinder()); 
+0

谢谢!我不知道这个功能。 – Dismissile 2011-03-02 17:29:29

+0

有一件事情可能仍然是一个问题:这不会影响客户端验证。目前,客户端验证阻止我提交,因为它是不正确的格式。 – Dismissile 2011-03-02 17:31:05

+0

@Dismissile,你用什么客户端验证?难道是jquery.validate插件与MS jquery.validate.unobtrusive? – 2011-03-02 17:52:08

0

如果你想要的格式只适用于显示器,然后设置ApplyFormatInEditMode为false。