简体   繁体   中英

MVC save empty string default value null

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编辑信息

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.

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.

为所有数据库varchar字段(例如'-')设置默认值,这样,只要不传递任何内容,插入就不会失败,因为字符串将采用默认值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM