0

我的一个控制器中有以下代码块,此代码返回两个日期字符串,这些日期字符串根据文化以某种方式格式化,以供我的视图使用。

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);
 } 

在视图代码中,我存储和使用视图数据。但是,如果字符串返回 null 我会收到错误消息。即使我将 dateTime 转换为字符串,null 也不会作为字符串返回吗?

var dateStringForSystem = ViewData["DateStringForSystem"];
var dateStringForActiveMetrics = ViewData["DateStringForActiveMetrics"];

    @if (dateStringForSystem == "")
    {
        // some html
    }
    else if (dateStringForActiveMetrics != "")
    {
       <span>@dateStringForActiveMetrics</span>
    }

对 C# 来说仍然很新,所以任何有关清理此代码的建议也非常感谢 :) 谢谢!

4

0 回答 0