asp.netasp.net-dynamic-datadynamic-data-site

Preventing empty strings becoming NULL in asp.net dynamic-data


I have a standard ASP.NET 4 Dynamic Data site (using Linq to SQL).

In my SQL-Server database I have hundreds of varchar fields that are set to NOT NULL, but have a default value of an empty string. They should never be NULL, but they may have an empty string as content.

When editing these fields on the dynamic data site, the internal logic sees the field as NOT NULL and somewhere between TextBox1.Text (which is an empty string) and calling the UPDATE sql it sets the value to NULL and they update fails.

I can see the System.Web.DynamicData.MetaColumn has a property 'ConvertEmptyStringToNull' but is is read-only.

What can I do to prevent the empty string becoming NULL without having to change properties for all the hundreds of fields?


Solution

  • In FieldTemplates/Text_Edit.ascx.cs change the behavior for strings, first remove the validators because they prevent the form from being submitted:

    protected void Page_Load(object sender, EventArgs e) {
        TextBox1.MaxLength = Column.MaxLength;
        if (Column.MaxLength < 20)
            TextBox1.Columns = Column.MaxLength;
        TextBox1.ToolTip = Column.Description;
    
        if (Column.IsString)
        {
            this.Controls.Remove(RequiredFieldValidator1);
            this.Controls.Remove(RegularExpressionValidator1);
            this.Controls.Remove(DynamicValidator1);
        }
        else
        {
            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);
        }
    }
    

    The piece of code that converts the empty string to NULL is somewhere in the ConvertEditedValue method, so skip that for strings:

    protected override void ExtractValues(IOrderedDictionary dictionary) 
    {
        if (Column.IsString)
        {
            dictionary[Column.Name] = TextBox1.Text;
        }
        else
        {
            dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
        }
    }
    

    Now you can update tables with empty strings, the problem of course is now you can set empty strings for all varchar fields not only the ones with a default value.

    I don't see anywhere in the Linq to SQL or EF datamodels where I can find out about my SQL-Server default value. There is a property DefaultValue but it is always NULL.