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.")]
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.– Vinícius Gobbo A. de Oliveira
Probably your decimal separator is the point, no?!
– Celso Marigo Jr
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.
– developer033
How is your VIEW and CONTROLLER?
– PauloHDSousa
@Paulohdsousa gave an edited in the topic, check there, grateful.
– developer033
In which line error occurs?
– Rodrigo Speller
@Rodrigospeller, I think I’ve solved the problem, thank you.
– developer033