0

My model comes from a SQL server database, where I have not allowed the fields to contain NULL. When editing one row in my MVC homepage I get as expected:

Cannot insert the value NULL into column 'husnr', table 'PrenSQL.dbo.adress'; column does not allow nulls. UPDATE fails.

So I googled some and found and added this to all string values.

[DisplayFormat(ConvertEmptyStringToNull = false)]

Now for some of my fields it seems to work, but not for others..

In my Edit GET request the empty fields are indeed empty. But in POST some are empty "" and some are null.

...
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Husnr { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Husbokstav { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Etage { get; set; }
...

POST Edit info

So I found this here in Stackoverflow but got the same error on the same fields.

My question is, how do I get these null fields to POST as empty strings?

EDIT: When I Create a new (in this case) Adress it will POST back the fields as empty.

Community
  • 1
  • 1
Rob
  • 186
  • 5
  • 18

2 Answers2

1

Try use for all String.Empty as default, not null values. Like in post Annotating properties on a model with default values

Notice, if you mark property as [Required] you will not be able to insert a record with empty string as value.

Edit

When I Create a new (in this case) Adress it will POST back the fields as empty.

You must add your properties on current form as hidden fields. Only this way values will be sent back by POST.

Community
  • 1
  • 1
Rayet
  • 298
  • 1
  • 11
0

set a default value for all your db varchar fields such as '-' so whenever nothing is passed to them insert will not fail as the string will take the default value.

Chirag K
  • 2,394
  • 2
  • 16
  • 23