Problem with Decimal (4,2)

4

I have an MVC project, I am using Entity Framkework and in my database there is a table with a column of type decimal (4,2) . The problem is:

I try to insert any value, for example: 5.00 // 5,00 // 14.21 // 14,21 and it always returns me this error:

  

Server Error in Application '/'. Can not convert an object   of type 'System.Decimal' in type 'System.String'. Description:   an unhandled exception during the execution of the current request of the   Review the stack trace for more information about   the error and where it originated in the code.

     

Exception Details: System.InvalidCastException: Can not   convert an object of type 'System.Decimal' to type 'System.String'.

Could anyone tell me what's wrong?

EDIT

Follow my model, controller and my view

  

Model:

[Required(ErrorMessage = "The {0} field is required.")]
[StringLength(5, ErrorMessage = "The {0} field can not contain more than 5 characters.")]
public decimal Percentage { get; set; }
  

Controller:

public ActionResult Create()
{
return View();
}

//
// POST: /Department/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Department department)
{
if (ModelState.IsValid)
{
db.Departments.Add(department);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(department);
}
  

View:

<div class="editor-label">
@Html.LabelFor(model => model.Percentage)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Percentage)
@Html.ValidationMessageFor(model => model.Percentage)
</div>

EDIT2

The problem is in the Model's DataAnnotation. I was trying to limit the field with [StringLength], tried with [MaxLength] tbm gives error, to limit the field and at the same time validate what should be typed, I used this DataAnnotation (Regex):

[RegularExpression(@"^(\d{1,2})(,\d{1,2})?$", ErrorMessage = "The field {0} is not in the correct format.")]
    
asked by anonymous 19.05.2015 / 15:29

1 answer

3

I would make a special Binder for decimals:

public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

Enroll in entire application:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    }
}

This resolves values for every decimal in the application.

    
19.05.2015 / 21:42