ASP.NET MVC 2 RC2 模型与 NVARCHAR NOT NULL 列绑定
请注意:我已经回答了我自己的问题,并附有类似问题答案的链接。一旦被允许,我就会接受这个答案(除非有人同时提出更好的答案)。
我有一个数据库列定义为 NVARCHAR(1000) NOT NULL DEFAULT(N'')
- 换句话说,默认值为空白的不可为 null 的文本列。
我有一个由 Linq-to-SQL 类设计器生成的模型类,它正确地将属性标识为不可为空。
我的视图中有一个 TextAreaFor
该属性。我在控制器中使用 UpdateModel
从表单中获取值并填充模型对象。
如果我查看网页并将文本区域留空,UpdateModel
坚持将该属性设置为 NULL
而不是空字符串。 (即使我在调用 UpdateModel
之前在代码中将该值设置为空白,它仍然会用 NULL
覆盖该值)。这当然会导致后续的数据库更新失败。
我可以在调用UpdateModel
后检查所有此类属性的NULL
,但这看起来很荒谬 - 肯定有更好的方法吗?
请不要告诉我我需要一个自定义模型绑定器来完成这样一个简单的场景......!
PLEASE NOTE: I've answered my own question with a link to an answer to a similar question. I'll accept that answer once I'm allowed to (unless anyone comes up with a better answer meantime).
I have a database column defined as NVARCHAR(1000) NOT NULL DEFAULT(N'')
- in other words, a non-nullable text column with a default value of blank.
I have a model class generated by the Linq-to-SQL Classes designer, which correctly identifies the property as not nullable.
I have a TextAreaFor
in my view for that property. I'm using UpdateModel
in my controller to fetch the value from the form and populate the model object.
If I view the web page and leave the text area blank, UpdateModel
insists on setting the property to NULL
instead of empty string. (Even if I set the value to blank in code prior to calling UpdateModel
, it still overwrites that with NULL
). Which, of course, causes the subsequent database update to fail.
I could check all such properties for NULL
after calling UpdateModel
, but that seems ridiculous - surely there must be a better way?
Please don't tell me I need a custom model binder for such a simple scenario...!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是重复的或类似的内容:
MVC 绑定表单数据问题
我担心需要定制模型绑定器。 ;)
Might be duplicate or something in the line of this:
MVC binding form data problem
I fear custom model binder will be necessary. ;)
您可能希望使用实体的部分类实现来实现该特定属性的属性更改处理程序。当您检测到该属性已更改为 NULL 时,只需将其更改为
string.Empty
即可。这样,只要将 NULL 分配给属性,它就会重置为空字符串。You might want to use a partial class implementation of your entity that implements the on property changed handler for that particular property. When you detect that the property has been changed to NULL, simply change it to
string.Empty
. That way anytime NULL is assigned to the property it gets reset to the empty string.