简体   繁体   English

ASP.NET C#空TextBox控件作为空字符串保存到数据库,我需要另存为null

[英]ASP.NET C# empty TextBox controls are saving to the database as empty strings, I need to save as null

During save I have an empty TextBox on my page because it is not required and the user decided not to fill it out. 保存期间,我的页面上有一个空的TextBox,因为它不是必需的,并且用户决定不填写它。

From what I remember in VB.NET when I do the following it will save to the database as NULL, but in C# it seems to be saving as an empty string. 从我记得在VB.NET中执行以下操作时,它将保存为NULL,但在C#中似乎将其保存为空字符串。 I am using Entity Framework 6 DB First 我先使用Entity Framework 6 DB

myobject.Phone = PhoneTextBox.Text

Do I really have to do the following for every single non required textbox during save? 保存期间,是否真的需要对每个非必需的文本框执行以下操作?

    if (string.IsNullOrEmpty(txtPhone.Text))
    {
        myobject.Phone = null;
    }
    else
    {
        myobject.Phone = PhoneTextBox.Text;
    }

if this is the case any suggestions on shortening the if statement or creating a function that takes care of it since it will always be the case when using textbox. 如果是这种情况,那么任何有关缩短if语句或创建可处理该语句的函数的建议都将得到解决,因为使用文本框时总是如此。

You could define this extension member: 您可以定义此扩展成员:

public static class Extensions
{
    public static string ToNullIfEmpty(this string @this)
    {
        return String.IsNullOrEmpty(@this) ? null : @this;
    }
}

And then you could do this: 然后您可以执行以下操作:

myobject.Phone = PhoneTextBox.Text.ToNullIfEmpty();

If PhoneTextBox.Text is an empty string and not null then, yes, you'll need to explicitly set a null value where you need one. 如果PhoneTextBox.Text是一个空字符串且不为null那么是的,您需要在需要的地方显式设置一个null值。 You can shorten it a little bit by using the conditional operator: 您可以使用条件运算符将其缩短一点:

myobject.Phone = string.IsNullOrEmpty(PhoneTextBox.Text) ? null : PhoneTextBox.Text;

What method are you using to store the data? 您使用什么方法存储数据? Entity Framework or your own stored procedure or sql insert? 实体框架还是您自己的存储过程或sql插入?

If you are rolling your own DAL then you must check for string.IsEmpty, in which case you can use DBNull.Value as the value to pass. 如果要滚动自己的DAL,则必须检查string.IsEmpty,在这种情况下,可以使用DBNull.Value作为要传递的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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