asp.net-mvc 如何设置TextBox空字符串的默认值而不是null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3475273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set default value of TextBox empty string instead of null
提问by arame3333
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.
但是,我发现对于强类型视图,用户在其中输入我要保存的对象的属性,如果未输入某些字段,则将它们分配为 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?
因此,不是将每个属性设置为空字符串,而是如何自动将表单上的每个 TextBox 设置为默认为空字符串而不是空字符串?
回答by Yngve B-Nilsen
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...
因此,每当有人发布带有空文本字段的表单时,这些将是一个空字符串而不是空...
回答by djdd87
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.
老实说,我会说您的编码方法已经过时且有缺陷。你应该处理所有的可能性,这并不难。这正是string.IsNullOrEmpty(value);
它的目的。
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
回答by Anders
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
如接受的答案中所述,在每个模型属性上使用属性的另一种解决方案是使用自定义模型绑定器,请参阅将 JSON 对象传递给 MVC 控制器时将 string.empty 转换为 null
回答by user3645143
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
因此,当您想确保任何为 null 的字符串变为空时,您可以使用它
yourString1.GetValueOrDefault();
yourString2.GetValueOrDefault();