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.")]