ASP.NET MVC Converting Null String to Zero Length

I am using MVC 3 and trying to get the fields left blank to send to the database as rows of zero length, not null. Is this possible with data annotation attributes?

If not, what is the best place to convert from zeros? Is this during model validation?

+4
source share
3 answers

I would not do this in the validator, but probably instead of binding to the model (or even in the model itself).

Often in my model classes I set the default string to empty for my string properties, and in my setters I convert zeros to empty strings.

It is very painful for me to write this repetitive material over and over, but it is much more pleasant not to deal with zeros.

0
source

Although not ideal, this is the best way I know: [DisplayFormat(ConvertEmptyStringToNull = false)] on the property. It preserves logic in a model, which is good practice, and it directly solves the problem. This is just a bummer that is necessary.

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

Set the property to string.empty in the constructor.

Or, although it's a little expensive, you can make an extension method that does the following and just calls 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); } 
0
source

Source: https://habr.com/ru/post/1344677/


All Articles