Chris
Chris

Reputation: 43

ASP.NET MVC Converting null to zero-length string

I'm using MVC 3 and attempting to get fields left blank to be sent to the database as zero-length strings, instead of nulls. Is this possible to do with data annotation attributes?

If not, what is the most appropriate place to convert from nulls? Is it during model validation?

Upvotes: 4

Views: 4213

Answers (3)

Kyle Robson
Kyle Robson

Reputation: 3060

While not ideal, this is the best way I know of: [DisplayFormat(ConvertEmptyStringToNull = false)] above the property. It keeps the logic in the model, which is good practice, and it directly addresses the issue. It's just a bummer that this is necessary.

private string _summary = "";
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public virtual string Summary
{
    get { return _summary; }
    set { _summary = value; }
}

Upvotes: 12

smartcaveman
smartcaveman

Reputation: 42246

Set the property equal to string.empty in the constructor.

Or, though this is a little more costly you could make an extension method that does the following and just call it in the constructor:

 var stringPropertyInfos = GetType()
                  .GetProperties(BindingFlags.Instance|BindingFlags.Public)
                  .Where(p => p.PropertyType == typeof(string));
 foreach(var propertyInfo in stringPropertyInfos){
     propertyInfo.SetValue(this,string.Empty,null);
 }

Upvotes: 0

James Nail
James Nail

Reputation: 1541

I wouldn't do this in a validator, but probably in model binding instead (or even in the model itself).

Often, in my model classes, I set my string properties to default to an empty string, and in their setters, I convert nulls to empty strings.

It's kindof a pain to write this repetitive stuff over and over, but it's so much nicer to not have to deal with nulls.

Upvotes: 0

Related Questions