在javascript中检查模型值是否为空或为null

时间:2018-08-13 09:25:06

标签: asp.net-mvc asp.net-core ternary-operator isnullorempty

这是我的代码

 <script>
 var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
 </script>

数据库中的值@myViewModel.myInfo.Name为空,但是此代码始终返回notNull
我如何正确地检查为空或为空?

2 个答案:

答案 0 :(得分:2)

这是当Razor和javascript混合在一起时发生的事情,所以不要养成经常这样做的习惯!

考虑这一行:

 <script>
 var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
 </script>

这里唯一的服务器端Razor件是@myViewModel.myInfo.Name,它返回null,将其呈现为空字符串。所以要给客户的是:

 <script>
 var _getValue = '' == null ? 'isNull' : 'notNull';
 </script>

现在这是纯js,并且在客户端执行,自然会给出'notNull'。毕竟,空字符串的确不是null。

现在考虑一下:

 <script>
 var _getValue = '@myViewModel.myInfo.Name' == '' ? 'isNull' : 'notNull';
 </script>

剃须刀片仍然相同,@myViewModel.myInfo.Name,仍然为空,因此向客户发送的是:

 <script>
 var _getValue = '' == '' ? 'isNull' : 'notNull';
 </script>

这次平等实际上成立了,所以你得到的是'isNull'。

要快速解决此问题,只需遵循evaluate expressions in Razor的通用语法:

 <script>
 var _getValue = '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")';
 </script>

现在,将在服务器端评估整个三元数据。

展望未来,您可能希望检出String方法IsNullOrEmptyIsNullOrWhitespace

答案 1 :(得分:2)

您应该将其添加到大括号中

例如

from scipy.stats import randint as sp_randint
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.datasets import load_boston
from sklearn.metrics import r2_score, make_scorer

X, y = load_boston().data, load_boston().target

X_train, X_test, y_train, y_test = train_test_split(X, y)

clf = RandomForestRegressor()

# Your custom scoring strategy
def my_custom_score(y_true, y_pred):
    return r2_score(y_true, y_pred)

# Wrapping it in make_scorer to able to use in RandomizedSearch
my_scorer = make_scorer(my_custom_score)

# Hyper Parameters to be tuned
param_dist = {"max_depth": [3, None],
              "max_features": sp_randint(1, 11),
              "min_samples_split": sp_randint(2, 11),}

random_search = RandomizedSearchCV(clf, param_distributions=param_dist,
                                   n_iter=20, scoring=my_scorer)
random_search.fit(X_train, y_train)

# Best found parameters set and model trained on X_train, y_train
best_clf = random_search.best_estimator_

# Get predictions on your new data
y_test_pred = best_clf.predict(X_test)

# Calculate your score on the predictions with respect to actual values
print(my_custom_score(y_test, y_test_pred))