Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
Chris Avatar asked Dec 17 '22 16:12

Chris


1 Answers

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; }
}
like image 170
Kyle Robson Avatar answered Jan 05 '23 01:01

Kyle Robson