gpt4 book ai didi

c# - MVC 模型绑定(bind) + 格式化

转载 作者:行者123 更新时间:2023-11-30 15:45:27 25 4
gpt4 key购买 nike

我的 MVC 应用程序中有一个模型 (Northwind),它有一个名为 UnitPrice 的属性:

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 时,它阻止我提交,因为它的格式不正确。如果我删除 $ 然后它会允许我。

有什么方法可以让它在尝试验证时忽略格式?

最佳答案

您可以为 Product 类型编写自定义模型联编程序并手动解析该值。以下是您可以如何继续:

型号:

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

Controller :

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!" />
}

Model Binder(这里是魔法发生的地方):

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);
}
}

Application_Start中注册模型绑定(bind)器:

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

关于c# - MVC 模型绑定(bind) + 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5169678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com