[英]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 . 我的模型来自一个SQL Server数据库,在该数据库中,我不允许字段包含NULL 。 When editing one row in my MVC homepage I get as expected: 在我的MVC主页中编辑一行时,我得到了预期的结果:
Cannot insert the value NULL into column 'husnr', table 'PrenSQL.dbo.adress'; 无法将值NULL插入表'PrenSQL.dbo.adress'的列'husnr'中; 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. 在我的Edit GET请求中,空白字段确实为空。 But in POST some are empty "" and some are null . 但是在POST中,有些为空“”,有些为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; }
...
So I found this here in Stackoverflow but got the same error on the same fields. 所以,我发现这个在这里,但#1登上了相同的字段相同的错误。
My question is, how do I get these null fields to POST as empty strings? 我的问题是,如何将这些空字段作为空字符串发送到POST?
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. 尝试将所有String.Empty用作默认值,而不是null值。 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. 注意,如果将属性标记为[Required],将无法插入以空字符串作为值的记录。
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. 只有这样,值才能通过POST发送回去。
为所有数据库varchar字段(例如'-')设置默认值,这样,只要不传递任何内容,插入就不会失败,因为字符串将采用默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.