Flater
Flater

Reputation: 13783

MVC 2 - Decimal value is not saved

I'm currently creating forms for contracts, one of the fields is for a rebate %, and has been declared a Decimal in Entity Framework. I'm getting an issue when I enter a value there and save it.

Quick overview of the code:

EF: tblContract -> Rebate is a Decimal field.

Create/Edit view:

<%: Html.TextBoxFor(model => model.Rebate, new { @class="form-txt-normal" }) %>

I've tried entering numbers in different ways.

75 : when I give it something that can be parsed to an int, it saves the correct value in the field (oddly, when displayed afterwards, no decimal point is shown, just 75).

75.25 : I watched the value that is passed to the [HttpPost] Edit method (same for Create). When a decimal value is entered, the variable is null. My outputscreen shows me an Exception has occured:

A first chance exception of type 'System.Linq.Dynamic.ParseException' occurred in ContractManagementTool.DLL

I also tried 75,25 to rule out culture settings about what a decimal point/comma should be, but the same issue occurs. I have several other fields which contains ints, they are handled in exactly the same way, with the only difference that Entity Framework knows them as Int32, not Decimal. The Int32 all work, the Decimal does not.

Am I missing something here? Can MVC not work with Decimals as it works with ints?

Further update:

I got part of it working. I haven't altered the code (except for some jQuery, I'll explain).

When I enter 75,25 the Rebate variable is properly passed to the method (which makes sense, as I'm in Belgium and we use , for decimal breaks :)) I added some jQuery to replace . with , when a user enters data, to make it easier.

When I post the variable, the decimal Rebate has value 75.25 (now EF takes over with its decimal point). Rebate is already in my tblContract entity that is passed to the method. I perform a db.ApplyCurrentValues(foo);

Now here's the punch line: in my database, the value 75 is saved. No decimal point, nothing. So I can pass it to my method properly now, but I cannot save it in the database.

Final update:

I solved it. For those curious about the answer: if you don't specify a scale of your decimal, it's 0. I seem to remember the standard was 2 for EF, but I might be mistaken.

Upvotes: 2

Views: 1809

Answers (1)

Flater
Flater

Reputation: 13783

Found it. Entity Framework set my decimal rounding to a whole number (1.0). Changed standard settings, problem solved :)

Upvotes: 1

Related Questions