我的控制器方法中有以下代码,用于向成员资格类型的列表视图提供数据:
[HttpGet]
public ActionResult SelectMembershipType(int clubId)
{
//Populate the list
var membershipTypes = from s in db.MembershipTypes
where (s.ClubId == clubId && s.Dormant == false)
orderby s.Type
select s;
//Generate the ViewModel with the appropriate membership types
var viewModel = membershipTypes.Select(t => new SelectMembershipTypeViewModel
{
//Select appropriate Cost based on current month
if(DateTime.Now.Month == t.ReducedMonth)
{
Cost = t.ReducedCost;
}
else
{
Cost = t.Cost;
}
ClubId = club.ClubId,
Name = club.Name,
MembershipName = t.Type,
MembershipType = t.MembershipTypeClassification.Type,
MembershipTypeId = t.MembershipTypeId,
});
return View(viewModel);
}
我输入的if语句不起作用会抛出几个错误。 我正在尝试将if语句应用于Cost的值,即如果今天的月份等于数据库中每个成员资格类型的ReducedMonth,则使Cost的值等于Membership Types ReducedCost值,如果不等于其等于相反,成本。 每个MembershipType可以具有不同的缩减月和成本
我不确定正确编码的正确语法
答案 0 :(得分:5)
我输入的if语句不起作用会抛出几个错误。
是的,它会 - 你把它放在一个对象初始化器中。对象初始值设定项不是任意代码块 - 它们基本上是property = value
赋值的列表。 (略多于此,但......)
幸运的是,在这种情况下,您可以使用条件运算符:
var viewModel = membershipTypes.Select(t => new SelectMembershipTypeViewModel
{
//Select appropriate Cost based on current month
Cost = DateTime.Now.Month == t.ReducedMonth ? t.ReducedCost : t.Cost,
ClubId = club.ClubId,
Name = club.Name,
MembershipName = t.Type,
MembershipType = t.MembershipTypeClassification.Type,
MembershipTypeId = t.MembershipTypeId,
});
这将编译,但由于将查询转换为SQL,它可能无法正常工作。您可能需要先提取DateTime.Now.Month
部分:
int month = Date.Now.Month;
var viewModel = membershipTypes.Select(t => new SelectMembershipTypeViewModel
{
//Select appropriate Cost based on current month
Cost = t.ReducedMonth == month ? t.ReducedCost : t.Cost,
ClubId = club.ClubId,
Name = club.Name,
MembershipName = t.Type,
MembershipType = t.MembershipTypeClassification.Type,
MembershipTypeId = t.MembershipTypeId,
});
请注意,DateTime.Now.Month
将是服务器时区中的月份...这绝对是您想要的吗?假设你希望它在特定的时区,我会明确地说明......否则你可能会遇到一些难以诊断的问题。