3

I have a simple application with asp.net mvc c# and I use EF code first.

I have a class "Student" that has a property of type decimal and others of type int. I dont undrestand why the decimal property will be not null without any data annotation?

Another problem is that when i run my application, the text box with decimal property retrieves a value of 170,6 but when I submit it, it shows an error which says that 170,6 is not a valid value and I have to change it to 170.6 to be able to submit.

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public int Weight { get; set; }
    public int changement { get; set; }

    public Grade Grade { get; set; }

}
public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}
Manoz
  • 6,507
  • 13
  • 68
  • 114
Mania
  • 59
  • 4
  • 2
    How could `decimal` be anything except not null? To be null you would need to use `decimal?` instead. – DavidG Jun 18 '18 at 09:28

2 Answers2

3

I dont understand why the decimal property will be not null without any data annotation

decimalin C# is a value type. It simply cannot be null. As would for instance int, double, DateTime.

170,6 is not a valid value and I have to change it to 170.6 to be able to submit.

That's a usual problem of Culture / Locale. I'm looking for a nice duplicate question on this topic, to give a useful link on how to solve this.

It's a bit tricky, because MVC has to generate the validation code that would be on client side to allow submitting, and the client could be configured with another culture.

EDIT : you can have a look at this question and it's accepted answer : MVC/JQuery validation does not accept comma as decimal separator

Pac0
  • 21,465
  • 8
  • 65
  • 74
2

For the first problem, a decimal is a value type, and can never be null. If you want it to be null, you should define it as decimal? (which is a shortcut for the Nullable<decimal> reference type wrapper). Make sure the corresponding field in the database is also NULL.

For the second problem, you should make sure your request thread runs at the same culture as your client. There are many ways to do it, try looking up on this site or google.

Tsahi Asher
  • 1,767
  • 15
  • 28