Problem with Decimal (4,2)

Asked

Viewed 643 times

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 always returns me this mistake:

Server Error in Application/'. Cannot convert an object of type 'System.Decimal' in type 'System.String'. Description: Occurred an exception without processing during the execution of the current Web. Examine stack tracking for more information on the error and where it originated in the code.

Exception Details: System.Invalidcastexception: Not possible convert an object of type 'System.Decimal' to type 'System.String'.

Could someone 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 was in Model 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.")]
  • 2

    Which database is used? What is the access language (C# with ADO.Net)? What is the definition of your table? What is the query running? Apparently you’re trying to insert a string in a numerical field, but without more detail of its problem and application, there is no way to know.

  • 1

    Probably your decimal separator is the point, no?!

  • I have a MVC 4 project, using SQL Server, Entity Framework, Decimal Blabla (4,2), I type this in the textbox of my form and try to register, hence returns me this error in the browser. @Celsomarigojr tried with everything, all return the same error.

  • How is your VIEW and CONTROLLER?

  • 1

    @Paulohdsousa gave an edited in the topic, check there, grateful.

  • In which line error occurs?

  • @Rodrigospeller, I think I’ve solved the problem, thank you.

Show 2 more comments

1 answer

3

I would make a Binder special to decimal places:

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

Register in the entire application:

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

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

This solves values for any and all application decimals.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.