如何获得模型绑定离开空字符串为空? [英] How to get model binder to leave null strings as null?

查看:98
本文介绍了如何获得模型绑定离开空字符串为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的SQL Server数据库具有一些可空的nvarchar的领域,包含空字符串没有nvarchar的领域。我想保持这种方式,但是默认的MVC模式粘结剂似乎把空字符串为空字符串。

My Sql Server database has some nullable nvarchar fields, and no nvarchar fields containing empty strings. I want to keep it this way, but the default MVC model binder seems to turn null strings into empty strings.

在控制器中检索空nvarchar的数据库字段,空场变成控制器内空字符串,并从那里的看法使他们,说为空白文本框。当页面发布,默认的模型绑定使用这些空白文本框更新模型,和以前空字符串更改为空字符串。当数据被更新到数据库,空值重写空字符串

When a controller retrieves a null nvarchar database field, the null field turns into null string inside the controller, and from there the view renders them, say as blank text boxes. When the page is posted, the default model binder uses these blank text boxes to update the model, and the formerly null strings are changed to empty strings. When the data is updated back to the database, nulls are overwritten with empty strings.

什么是让模型绑定离开这些空不变,最简单的方法?

What is the easiest way to get model binding to leave these nulls unchanged?

推荐答案

我张贴这个答案在这个问题上坚持到底。用它工作了一段时间后,我来看看这个问题,模型的完整性的普遍关注的一部分。有一段时间,我已经实现我的更新存储过程中的一个解决方案,以赶上空字符串,并将其转空,沿着mikerennick的回答上面的线。后来我想也确保字段被修剪和我发生在应用程序移到NHibernate的(和大多数的存储过程走了)。最后,我嵌入式POCO的一些逻辑来修剪和检查空字符串(不论来自何方)的制定者像这样:

I'm posting this answer to follow through on this question. After working with it for a while I came to see this problem as part of the general concern of model integrity. For a while I had implemented a solution inside my update stored procedures to catch empty strings and turn them to nulls, along the lines of mikerennick's answer above. Later I wanted also to make sure fields were trimmed and I happened to move the application to NHibernate (and most of the stored procedures went away). In the end I embedded some POCO logic to trim and check for empty strings (from whatever source) in the setters as so:


public MyClass {
  private string _name;
  public string Name {
    get { return _name; }
    set { _name = value.TrimToNullIfEmpty(); }
  }
}

public static class StringExtensions {
  public static string TrimToNullIfEmpty(this string s) {
    string temp = (s ?? "").Trim();
    return temp.Length == 0 ? null : temp;
  }
}

这篇关于如何获得模型绑定离开空字符串为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆