我在我的一个控制器中有以下代码块,此代码返回两个日期字符串,这些日期字符串根据我的View消费文化以某种方式格式化。
string dateStringForSystem = "";
string dateStringForActiveMetrics = "";
string cultureConfigKey = System.Configuration.ConfigurationManager.AppSettings["InstanceCulture"];
DateTime? lastEntryDateForSystem = null;
DateTime? lastEntryDateForActiveMetrics = null;
DataSet dSet = DataHelper.Measurements_GetLastMeasurement(userSession.UserIDNative);
foreach (DataRow dr in dSet.Tables[0].Rows)
{
lastEntryDateForSystem = (DateTime?)dr["LastMeasurementWhen"];
lastEntryDateForActiveMetrics = (DateTime?)dr["LastMeasurementForActiveGoalsWhen"];
}
// Format viewdata dates based on culture and convert it to string
if (cultureConfigKey == "en" )
{
ViewData["DateStringForSystem"] = dateStringForSystem = String.Format("{0:MM/dd/yy}", lastEntryDateForSystem);
ViewData["DateStringForActiveMetrics"] = dateStringForActiveMetrics = String.Format("{0:MM/dd/yy}", lastEntryDateForActiveMetrics);
}
else
{
ViewData["DateStringForSystem"] = dateStringForSystem = String.Format("{0:dd/MM/yy}", lastEntryDateForSystem);
ViewData["DateStringForActiveMetrics"] = dateStringForActiveMetrics = String.Format("{0:dd/MM/yy}", lastEntryDateForActiveMetrics);
}
在View代码中,我存储并使用视图数据。但是如果字符串返回null我就会收到错误。即使我将dateTime转换为字符串,null也不会作为字符串返回吗?
var dateStringForSystem = ViewData["DateStringForSystem"];
var dateStringForActiveMetrics = ViewData["DateStringForActiveMetrics"];
@if (dateStringForSystem == "")
{
// some html
}
else if (dateStringForActiveMetrics != "")
{
<span>@dateStringForActiveMetrics</span>
}
对于C#来说还是一个新手,所以有关清理此代码的任何建议也非常感谢:)谢谢!