你可以写为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());
您使用ApplyFormatInEditMode =真的吗? – swapneel 2011-03-02 15:59:02
是的。我正在使用它。 – Dismissile 2011-03-02 16:12:25