我假设你在你的模型/视图模型类上使用某种类型IEnumerable
来填充下拉列表中的项目。当您构建此列表时,只需添加“(当前)”和“(最新)”选项,然后将模型返回到您的视图。如果FinancialPeriod
是这样的模型/视图模型类:
public class FinancialPeriod{
public int FinancialPeriodId { get; set; }
public string DisplayText { get; set; }
}
然后您可以在您的控制器中执行此操作,假设您从数据库中检索到的所有财务期间的列表是您模型上的一个属性,称为FinancialPeriods
:
public ActionResult Index(){
var model = GetTheModel();
model.FinancialPeriods.Add(new FinancialPeriod{
FinancialPeriodId = <something>,
DisplayText = "(Current)"
};
model.FinancialPeriods.Add(new FinancialPeriod{
FinancialPeriodId = <somethingElse>
DisplayText = "(Latest)"
};
return View(model);
}
确保在模型回发到控制器时替换值<something>
并且<somethingElse>
可以正确解释。
编辑 - 根据您的评论和编辑,这样的内容更合适:
public ActionResult Index(){
var model = GetTheModel();
var currentMonth = DateTime.Now.Month;
var previousMonth = currentMonth - 1;
if (previousMonth == 0)
previousMonth = 12;
var currentPeriod = "Period " + currentMonth.ToString();
var latestPeriod = "Period " + previousMonth.ToString();
var newList = new List<FinancialPeriod>();
foreach(var period in model.FinancialPeriods){
if(period.DisplayText == currentPeriod)
{
newList.Add(new FinancialPeriod
{
FinancialPeriodId = period.FinancialPeriodId,
DisplayText = period.DisplayText + " (Current)"
};
continue;
}
if(period.DisplayText == latestPeriod)
{
newList.Add(new FinancialPeriod
{
FinancialPeriodId = period.FinancialPeriodId,
DisplayText = period.DisplayText + " (Latest)"
};
continue;
}
newList.Add(period);
}
model.FinancialPeriods = newList;
return View(model);
}