ASP.NET MVC Converting null to zero-length string

2019-06-27 00:54发布

问题:

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?

回答1:

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.



回答2:

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; }
}


回答3:

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);
 }