ASP.NET MVC 2 RC2 模型与 NVARCHAR NOT NULL 列绑定

发布于 2024-08-27 21:24:56 字数 652 浏览 5 评论 0原文

请注意:我已经回答了我自己的问题,并附有类似问题答案的链接。一旦被允许,我就会接受这个答案(除非有人同时提出更好的答案)。

我有一个数据库列定义为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

讽刺将军 2024-09-03 21:24:57

可能是重复的或类似的内容:

MVC 绑定表单数据问题

我担心需要定制模型绑定器。 ;)

Might be duplicate or something in the line of this:

MVC binding form data problem

I fear custom model binder will be necessary. ;)

尐偏执 2024-09-03 21:24:57

您可能希望使用实体的部分类实现来实现该特定属性的属性更改处理程序。当您检测到该属性已更改为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文