How to set default value of TextBox empty string instead of null

女生的网名这么多〃 提交于 2019-11-27 02:32:37

问题


I may be out of date, but one principle I adhere to is avoid nulls as much as possible.

However what I have found is that for a strongly typed view in which the user inputs the properties of an object I want to save, if some fields are not entered they are assigned as null.

Then when you try to save the changes, the validation fails.

So rather than set each property to an empty string, how can I automatically set each TextBox on a form to default to an empty string rather than a null?


回答1:


You could put the following attribute on your string-properties in your model:

[DisplayFormat(ConvertEmptyStringToNull=false)]

So whenever someone posts a form with empty text-fields, these will be an empty string instead of null...




回答2:


To be honest, I'd say your coding methodology is out of date and flawed. You should handle all possibilities, it's not hard. That's exactly what string.IsNullOrEmpty(value); is for.

I'm guessing your validation logic is something like:

if (value == string.Empty) { isValid = false; } 

So it doesn't handle the null values. You should replace that check so it also checks for nulls.

string value1 = null;
string value2 = string.Empty;

string.IsNullOrEmpty(value1); // true
string.IsNullOrEmpty(value2); // true



回答3:


An alternative solution to using attributes on each model property, as described in the accepted answer, is using a custom model binder, see string.empty converted to null when passing JSON object to MVC Controller




回答4:


I ran across this problem when dealing with an old service that requires empty strings. I created an extension method:

public static string GetValueOrDefault(this string str)
        {
            return str ?? String.Empty;
        }

So you can use this when you want to make sure any strings that are null become empty

yourString1.GetValueOrDefault();
yourString2.GetValueOrDefault();


来源:https://stackoverflow.com/questions/3475273/how-to-set-default-value-of-textbox-empty-string-instead-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!