我正在ASP.NET MVC 5中的一个项目上工作。我有一个ViewModel
public class AcademicYearListViewModel
{
public Guid Id { get; set; }
[Display(Name = "Academic Year")]
public int StartYear
{
get { return this.StartDate.Year; }
}
public int EndYear
{
get { return this.EndDate.Year; }
}
[Display(Name = "Start date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime StartDate { get; set; }
[Display(Name = "End date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime EndDate { get; set; }
[Display(Name = "Active")]
public bool IsActive { get; set; }
}
在ViewModel中,我想从StartDate和EndDate中提取Year。然后将结果连接起来,并用反斜杠将其分开。结果应该是字符串,看起来像这样:2008/2009。
答案 0 :(得分:0)
您可以添加另一个只读属性,即可完成工作
[Display(Name = "End date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime EndDate { get; set; }
[Display(Name = "Start date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime StartDate { get; set; }
[Display(Name = "concanate")]
public string dateTime { get {
return StartDate.Year + "/" + EndDate.Year;
} }
答案 1 :(得分:0)
您可以创建一个仅吸气的属性,并使用字符串连接为其分配,如以下示例所示:
1)使用标准串联
public string ConcatDate
{
get
{
return StartDate.Year + "/" + EndDate.Year;
}
}
public string ConcatDate
{
get
{
return StartYear + "/" + EndYear;
}
}
2)使用string.Format()
public string ConcatDate
{
get
{
return string.Format("{0}/{1}", StartDate.Year, EndDate.Year);
}
}
3)使用字符串插值(C#6 +)
public string ConcatDate
{
get
{
return $"{StartYear}/{EndYear}";
}
}
演示示例:.NET Fiddle