MVC model binding + formatting

I have a model (Northwind) in my MVC application that has the UnitPrice property:

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

In my opinion, I want to display this as the currency {0: C}. I tried using DataAnnotations DisplayFormatAttribute: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx

It worked fine for display, but when I try and POST, it prevents me from sending because it is not in the correct format. If I remove $, it will allow me.

Is there a way so that it can ignore the format when trying to check?

+3
source share
2 answers

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

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:

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

, , ApplyFormatInEditMode false.

0

Source: https://habr.com/ru/post/1795762/


All Articles