如果内部列表视图控制器的方法声明
问题描述:
我有我的控制器方法中下面的代码来提供数据,列表视图会员类型:如果内部列表视图控制器的方法声明
[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类型使成本的值等于成员资格类型ReducedCost值,如果不是使其等于其成本代替。 每个MembershipType可以有不同的减小月份与成本
我不知道正确的语法的实现代码正确
答
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
将在服务器这里的时区的月份是......绝对你想要什么?假设你希望它在特定的时区,我会明确表示......否则你可能会遇到一些难以诊断的问题。
+0
非常感谢乔恩,第一个选项完美运作。感谢你的解释,现在它变得更有意义。 –
什么是确切的错误信息? – ekad
您的问题已回答两次:http://*.com/questions/2234091/object-initializer-and-dynamically-specifying-properties和http://*.com/questions/3229188/c-sharp-initialiser-有条件分配 –